Sergey
Sergey

Reputation: 1660

Toggle mdTooltip via event instead of hover

I'm usingmdTooltip on an icon - hovering over it displays the tooltip.

enter image description here

How can show the tooltip without the user hovering (e.g. When an an event occurs)

Looking at the documentation for MD tooltip, it appears that this is possible by using the toggle method.

I'm new to Angular and Material Design. What's the syntax and how can I achieve this?

Below is my template:

<md-icon mdTooltip="{{errorMessage}}" (mdTooltipToggle)="myVar">warning</md-icon>

I know that's totally off, but I'm guessing I need an event that I fire, that will trigger toggle() - but how?


Edit

Ok I understand that I can select the mdTooltip "thing" (what's that called anyways, an element, directive or "attribute directive" etc.?) using @ViewChild and it'll select the first instance of the tooltip, but what if I have multiple icons with mdTooltip's?

For example if I have:

<md-icon iconOne *ngIf="isGood"  mdTooltip="{{message}}">check</md-icon>
<md-icon iconTwo *ngIf="!isGood" mdTooltip="{{errorMessage}}">warning</md-icon>

How can I toggle only the tooltip on the 2nd icon?

I posted another question since it deviates slightly from this one: Select specific attribute directive using ViewChild in Angular

Upvotes: 0

Views: 907

Answers (1)

Gr&#233;gory Gossart
Gr&#233;gory Gossart

Reputation: 837

Here is a Plunker to show you how to achieve that : https://plnkr.co/edit/AdY0WU8fMeROE4lxKYSM?p=preview

@ViewChild(MdTooltip) tooltip;

This @ViewChild looks for a MdTooltip directive inside your template and save it under the tooltip attribute.

ngAfterViewInit() {
    this.tooltip.show(0);
}

Then, you can access it during the AfterViewInit phase and call show, hide or toggle methods on it.

Please note that the above Plunkr only work when you have only one tooltip in your template (because of the @ViewChild(MdTooltip), as it grabs the first MdTooltip directive it finds). If you need to do it with several tooltips, you will need to use the # notation to grab the tooltip you need.

EDIT :

I noticed that my Plunkr did not answer exactly your question. You wanted the tooltip to be toggled ONCE a server error is triggered.

I wrote another version of my Plunkr : https://plnkr.co/edit/s3Ykz0B8D7r1U6paLWmF?p=preview

In this version, I do not trigger the display of the tooltip instantly. I simulate an Observable that will "make an error happen" after 3 seconds. That will change your icon AND toggle the tooltip display.

I explained that in the comments of ngOnInit function.

Upvotes: 2

Related Questions