Angular Mattooltip Condition Inside Interpolation

I am adding an angular condition for my MatToolTip. At first this following works for just 1 string assignment

matToolTip={{myData.name}}

But I need to add a condition like the following

matToolTip={{ myData.hasName : myData.name, myData.hasNoName : myData.NoNameMessage }}

The data coming in has one or the other, never both.

I found another stackoverflow which ppl says the following works but not in my Angular 7 code

{{element.source == 1 ? 'upwork' : (element.source == 2 ? 'refer from friend' : '')}}

I tried putting them in single quote but no success. any help is greatly appreciated. Thanks.

3 Answers

Try this:

[matTooltip]="myData.hasName ? myData.name : (myData.hasNoName? 'myData.NoNameMessage' : null)"

1

You can use the [matTooltipDisabled] directive instead of using a ternary operator or other more complex solution.

An example:

<mat-icon matTooltip="It's closed."
  [matTooltipDisabled]="entity.isOpen == true">
    close
</mat-icon>
1

You can also use interpolation to call a typescript function on component class that will perform complex if-else scenarios. Something like this..

<button mat-raised-button
    matTooltip={{getToolTip(source)}}
    >

Action

getToolTip(source)  
{
var tooltip = '';
if(source==1)
{
  tooltip = 'upwork';
}
else
{
  if(source==2){
    tooltip = 'refer from friend';
  }
}
return tooltip;
}
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest