šŸ™ˆšŸ–±ļøBuild a Zoo with Angular Material Tooltip

Angular Material offers many useful features for frontend developers. Today we’ll talk about a handy component: the tooltip. This is very useful for displaying information about an element on your page with a simple mouse hover. Read on for a step-by-step tutorial with an easy example of the tooltip component from Angular Material.

Procedure

As in previous tutorials, let’s first install Node and npm:

Set up the Angular project by installing the Angular CLI tool:

npm install -g @angular/cli

Create a project called my-tooltip:

ng new my-tooltip

Enter the project directory:

cd my-tooltip

Install Angular Material:

ng add @angular/material

To demonstrate, we’ll display some animals with their name shown in the tooltip.

app.ts

import { Component } from '@angular/core';
import { MatTooltipModule } from '@angular/material/tooltip';

interface Animal {
  name: string;
  icon: string;
}

@Component({
  selector: 'app-root',
  imports: [MatTooltipModule],
  templateUrl: './app.html',
  styleUrl: './app.css',
})
export class App {
  animals: Animal[] = [
    { name: 'Elephant', icon: '🐘' },
    { name: 'Hippopotamus', icon: 'šŸ¦›' },
    { name: 'Giraffe', icon: 'šŸ¦’' },
    { name: 'Lion', icon: '🦁' },
    { name: 'Zebra', icon: 'šŸ¦“' },
  ];
}

app.html

@for (animal of animals; track animal.name) {
<div
  #tooltip="matTooltip"
  matTooltip="{{animal.name}}"
  [matTooltipPosition]="'right'"
  class="animal"
>
  {{animal.icon}}
</div>
}

app.css

.animal {
    width: 100px;
    height: 100px;
    font-size: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
}

Here is the result in the browser:

Conclusion

Now you’ve seen a basic example of how to use the Angular Material tooltip component in your web project. Happy Coding!

Leave a comment