Demo
Angular CDK setup
The first step is to add a library. Write the command below to add @angular/cdk to your project.
The second step is to add overlay styles to the global stylesheet file (styles.scss).
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.
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
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
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
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.