在Angular 18中如何显示带箭头的多个工具提示
我在用Angular的 ngx-bootstrap尝试显示多个工具提示(tooltip),但不工作。每条工具提示的信息的箭头也没有正常显示。
把ng-template作为工具提示的内容使用。如何解决这个问题?
这是我的代码——需要更新哪些地方才能让它工作?
app.component.html:
<button
class="sr-info-icon-set sr-info-control"
style="margin: auto;"
[tooltip]="staticHtmlTooltip"
container="body"
placement="auto"
(click)="toggleTooltip()"
triggers=""
>
Info
</button>
<ng-template #staticHtmlTooltip>
<div class="tooltip-content">
<div>Your content here...</div>
<div>More content if needed...</div>
<button
class="btn btn-xs btn-default"
(click)="closeInfo(); $event.stopPropagation()"
>
Close
</button>
</div>
</ng-template>
<button
class="sr-info-icon-set sr-info-control"
style="margin: auto;"
[tooltip]="staticHtmlTooltip2"
container="body"
placement="auto"
(click)="toggleTooltip2()"
triggers=""
>
Info2
</button>
<ng-template #staticHtmlTooltip2>
<div class="tooltip-content2">
<div>Your content here...</div>
<div>More content if needed...</div>
<button
class="btn btn-xs btn-default"
(click)="closeInfo2(); $event.stopPropagation()"
>
Close
</button>
</div>
</ng-template>
app.component.ts:
import { Component, ViewChild } from '@angular/core';
import { TooltipDirective } from 'ngx-bootstrap';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChild(TooltipDirective) tooltip?: TooltipDirective;
@ViewChild(TooltipDirective) tooltip2?: TooltipDirective;
isTooltipOpen = false;
isTooltipOpen2 = false;
toggleTooltip(): void {
if (this.isTooltipOpen) {
this.tooltip?.hide();
} else {
this.tooltip?.show();
}
this.isTooltipOpen = !this.isTooltipOpen;
}
closeInfo(): void {
this.tooltip?.hide();
this.isTooltipOpen = false;
}
toggleTooltip2(): void {
if (this.isTooltipOpen2) {
this.tooltip2?.hide();
} else {
this.tooltip2?.show();
}
this.isTooltipOpen2 = !this.isTooltipOpen2;
}
closeInfo2(): void {
this.tooltip2?.hide();
this.isTooltipOpen2 = false;
}
}
演示:https://stackblitz.com/edit/ngx-bootstrap-example-x5qtn2rn?file=app%2Fapp.component.html
解决方案
所以,你在使用多个实例,但你只引用了第一个指令实例,因此会出现这里的行为。
@ViewChild(TooltipDirective) tooltip?: TooltipDirective;
@ViewChild(TooltipDirective) tooltip2?: TooltipDirective;
因此,你需要引用每个实例,可以通过为每个工具提示添加模板引用来实现:
<button
...
#t1="bs-tooltip"
<button
...
#t2="bs-tooltip"
但如果你只引用模板变量,这种做法就会失败,因为你其实想要引用每个元素的 directive,可以通过在 ViewChild 中添加 read 选项来读取该指令:
@ViewChild('t1', {read:TooltipDirective}) tooltip?: TooltipDirective;
@ViewChild('t2', {read:TooltipDirective}) tooltip2?: TooltipDirective;
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。