Tooltips communicate additional information about an input or a button when the user hovers, focuses, or taps on an element. Intended to provide comfort to your users, there’s a right way and a wrong way to use tooltips.
Number one, don’t restate what’s already visible in the tooltip again, and avoid using rich information like images or hyperlinks in your tooltips. You want to avoid your tooltips being the primary way users get information about your app.
Remember, tooltips are a secondary help utility. Tooltips should be transient, meaning they appear and disappear without any interaction from the user.
Tooltips should show up below where the mouse is hovering, and the tooltip text should always be centered below the component. Adding a tooltip to our application is a piece of cake. From Visual Studio Code, let’s Command + P and open up the messages module. And if you remember, we have a little continue icon, a right icon, and let’s just go ahead and make that a little bit more intuitive and add a secondary tooltip, which will tell people that that is the continue icon. On line 16, we’ll import MatTooltipModule from @angular/material/tooltip.
Now we’ll scroll down to our imports, and on line 31 I’ll add a comma, and I’ll add the MatTooltipModule here. Save that, and I’ll Command + P and go to the message-new.component.html. And from here, I’ll scroll down to the continue icon, which is at the bottom of this form on line 29 for me. And on line 28, where the button is, let’s just go ahead and set our tooltip, which is as simple as saying matTooltip=”Continue”. Now I’m going to save that, and let’s go ahead and run the application with npm starts.
And now, when I mouse over my continue icon, I see I have the word Continue show up here, which is exactly what I want. Well, suppose I want to customize this a little bit more. You know, that Continue font is a little bit small here. Let’s say I want to customize my tooltip a bit. So let’s return to our Visual Studio Code, and let’s go ahead and add a new directive here, called matTooltipClass. And we’re just going to call this our example-tooltip. And I’m going to Command + P and I’ll put up my main style sheet in styles.css.
And I’m just going to go ahead and add a class here, example-tooltip, and let’s set the font size to 90%. Save this, go back to our application, refresh the page, and I’ve made my font a little bit bigger. I can customize this even more if I want to. I can use the background and make it purple if I wanted to. I mouse over it, now I have purple. Don’t go crazy with this, again, we don’t want to put rich media in our tooltips, it’s a secondary help. So increasing the font size, I think, is helpful, but maybe not all the colors, so let’s just remove this and go back to the way it was.
And we’ve added a tooltip to our application.