I'm trying to implement a copy to clipboard button that shows a tooltip on hover.
When I hover over the button for the first time, it should show the tooltip "Copy" and if I click on the button, the tooltip should become "Copied!" without disappearing.
I'm not able to implement this behavior as the tooltip closes once I click on the button, and I need to mouseout from the button and then hover over it again to see the "Copied!" tooltip. My guess is that it's because clicking on the button triggers the mouseout event, so the tooltip thinks that I have left the button element, but I have no idea how to overwrite this behavior.
My code:
.html
<button type="button" (click)="copy()"
[ngbTooltip]="tooltipText"
triggers="hover focus"
>
</button>
.ts
import { Clipboard } from '@angular/cdk/clipboard';
@Component({
...
})
export class CopyButtonComponent {
tooltipText = 'Copy';
constructor(private clipboard: Clipboard) {}
copy(): void {
this.clipboard.copy('text');
this.tooltipText = 'Copied!';
}
}
First of all, Use triggers
property and value should be manual
Then, In order to make tooltip behaviour use mouseover
and mouseleave
events. Also, take reference of the tooltip in order to make tooltip hide and show.
Then, for tooltip content use ng-template
. By using ng-template you'll have update text immediately.
Here, in your case, you just need to update your html file.
Updated .html
<button type="button" (click)="copy()"
[ngbTooltip]="tolTemplate"
#t="ngbTooltip"
(mouseover)="t.open()"
(mouseleave)="t.close()"
>
</button>
<ng-template #tolTemplate>{{ tooltipText }}</ng-template>