英文:
How to prevent ngbTooltip from disappearing on click
问题
我正在尝试实现一个复制到剪贴板的按钮,在悬停时显示工具提示。
当我首次悬停在按钮上时,它应该显示工具提示 "复制",如果我点击按钮,工具提示应该变成 "已复制!" 而不消失。
我无法实现这个行为,因为一旦我点击按钮,工具提示就会关闭,我需要从按钮上移开鼠标,然后再次悬停在上面才能看到 "已复制!" 工具提示。我猜测这是因为点击按钮触发了鼠标移出事件,因此工具提示认为我已经离开了按钮元素,但我不知道如何覆盖这种行为。
我的代码:
.html
<button type="button" (click)="copy()"
[ngbTooltip]="tooltipText"
triggers="hover focus"
>
</button>
.ts
import { Clipboard } from '@angular/cdk/clipboard';
@Component({
...
})
export class CopyButtonComponent {
tooltipText = '复制';
constructor(private clipboard: Clipboard) {}
copy(): void {
this.clipboard.copy('text');
this.tooltipText = '已复制!';
}
}
英文:
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!';
}
}
答案1
得分: 0
首先,使用 triggers
属性,其值应设置为 manual
。
然后,为了实现工具提示行为,请使用 mouseover
和 mouseleave
事件。还要引用工具提示以实现工具提示的隐藏和显示。
接下来,用 ng-template
来设置工具提示的内容。通过使用 ng-template,您将能够立即更新文本。
在您的情况下,您只需要更新您的 HTML 文件。
更新后的 .html
<button type="button" (click)="copy()"
[ngbTooltip]="tolTemplate"
#t="ngbTooltip"
(mouseover)="t.open()"
(mouseleave)="t.close()"
>
</button>
<ng-template #tolTemplate>{{ tooltipText }}</ng-template>
演示: https://stackblitz.com/edit/angular-ps2wah
英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论