How to create a tooltip with @angular/cdk

See how to create a simple but powerful tooltip directive using the `@angular/cdk` and `OverlayModule`.

You can view the source code for this project by following this link: GitHub

Demo

1
<button appTooltip="Hello from string">Tooltip as string</button>
2
3
<svg [appTooltip]="templateForTooltip">
4
<!-- ... -->
5
</svg>
6
<ng-template #templateForTooltip> <strong>Hello</strong> from template </ng-template>

Angular CDK setup

The first step is to add a library. Write the command below to add @angular/cdk to your project.

Install @angular/cdk
1
ng add @angular/cdk

The second step is to add overlay styles to the global stylesheet file (styles.scss).

styles.scss
1
@import "~@angular/cdk/overlay-prebuilt.css";

This file is very small. This weight is around 1.2 kB.

From @angular/cdk@15 OverlayModule is not required to import anymore because Overlay is provided into root.

Creating directive

The directive is responsible for creating a component above (or below if above is no place) an element. As you can see, a tooltip is created on focus or moveenter events. After blur or moveleave the tooltip is destroyed.

tooltip.directive.ts
1
@Directive({
2
selector: "[appTooltip]",
3
standalone: true,
4
})
5
export class TooltipDirective implements OnDestroy {
6
private element = inject<ElementRef<HTMLElement>>(ElementRef);
7
private overlay = inject(Overlay);
8
private viewContainer = inject(ViewContainerRef);
9
10
@Input() appTooltip!: TooltipData;
11
12
private overlayRef: OverlayRef | null = null;
13
14
@HostListener("mouseenter")
15
@HostListener("focus")
16
showTooltip(): void {
17
if (this.overlayRef?.hasAttached() === true) {
18
return;
19
}
20
21
this.attachTooltip();
22
}
23
24
@HostListener("mouseleave")
25
@HostListener("blur")
26
hideTooltip(): void {
27
if (this.overlayRef?.hasAttached() === true) {
28
this.overlayRef?.detach();
29
}
30
}
31
32
ngOnDestroy(): void {
33
this.overlayRef?.dispose();
34
}
35
36
private attachTooltip(): void {
37
if (this.overlayRef === null) {
38
const positionStrategy = this.getPositionStrategy();
39
this.overlayRef = this.overlay.create({ positionStrategy });
40
}
41
42
const injector = Injector.create({
43
providers: [
44
{
45
provide: TOOLTIP_DATA,
46
useValue: this.appTooltip,
47
},
48
],
49
});
50
const component = new ComponentPortal(TooltipContainerComponent, this.viewContainer, injector);
51
this.overlayRef.attach(component);
52
}
53
54
private getPositionStrategy(): PositionStrategy {
55
return this.overlay
56
.position()
57
.flexibleConnectedTo(this.element)
58
.withPositions([
59
{
60
originX: "center",
61
originY: "top",
62
overlayX: "center",
63
overlayY: "bottom",
64
panelClass: "top",
65
},
66
{
67
originX: "center",
68
originY: "bottom",
69
overlayX: "center",
70
overlayY: "top",
71
panelClass: "bottom",
72
},
73
]);
74
}
75
}

Take a look at passing data between the component and the directive. To do it, I used Injector with a custom provider.

Look at getPositionStrategy function

  • in flexibleConnectedTo I defined a position connection between the directive and the tooltip,
  • In withPositions I defined available positions. If the first position does not fit on a screen, then use the second one

Tooltip container component

tooltip-container.component.ts
1
@Component({
2
selector: "app-tooltip-container",
3
templateUrl: "./tooltip-container.component.html",
4
styleUrls: ["./tooltip-container.component.scss"],
5
changeDetection: ChangeDetectionStrategy.OnPush,
6
standalone: true,
7
imports: [NgTemplateOutlet],
8
})
9
export class TooltipContainerComponent {
10
tooltipData = inject<TooltipData>(TOOLTIP_DATA);
11
12
isString(value: TooltipData): value is string {
13
return typeof value === "string";
14
}
15
16
isTemplate(value: TooltipData): value is TemplateRef<void> {
17
return this.tooltipData instanceof TemplateRef;
18
}
19
}
tooltip-container.component.html
1
@let data = tooltipData;
2
3
@if (isString(data)) {
4
{{ data }}
5
} @else {
6
<ng-template [ngTemplateOutlet]="data" />
7
}

Take a look at asString and asTemplate getters. In HTML is not possible to cast a type, so I used a pattern with *ngIf.

Adding styles for tooltip

tooltip-container.component.scss
1
:host {
2
display: block;
3
max-width: 12rem;
4
padding: 0.7rem;
5
font-size: 0.85rem;
6
color: #fff;
7
background: #000;
8
border-radius: 0.25rem;
9
box-sizing: border-box;
10
}
11
12
:host-context(.top) {
13
margin-bottom: 0.5rem;
14
}
15
16
:host-context(.bottom) {
17
margin-top: 0.5rem;
18
}

Styles to make a tooltip float are shipped by global styles, so I do not need to it on my own hands.

Info about the current position of the tooltip I took from CSS classes like top and bottom (defined in a panelClass parameter in getPositionStrategy function). Thanks to that, I can apply different styles if the tooltip is above or below the element.

Q&A

How to implement a fallback position strategy

tooltip.directive.ts
1
@Directive({
2
selector: "[appTooltip]",
3
standalone: true,
4
})
5
export class TooltipDirective implements OnDestroy {
6
// ...
7
8
private getPositionStrategy(): PositionStrategy {
9
return this.overlay
10
.position()
11
.flexibleConnectedTo(this.element)
12
.withPositions([
13
{
14
originX: "center",
15
originY: "top",
16
overlayX: "center",
17
overlayY: "bottom",
18
panelClass: "top",
19
},
20
{
21
originX: "center",
22
originY: "bottom",
23
overlayX: "center",
24
overlayY: "top",
25
panelClass: "bottom",
26
},
27
]);
28
}
29
}

As you can see, we have two positions (array with two elements). That means the overlay will try to put an element using the first position. When the element will not fit on the screen then the overlay will take the second position. If the second will not fit, the overlay will take the third one (and so on). When there are no more positions then the last one will be applied. All that means, if you want to define a fallback position strategy just add the new position into the end of the array.

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Leave a comment