【发布时间】:2021-04-07 15:24:49
【问题描述】:
我正在尝试实现一些我必须在单击按钮时打开一个弹出窗口的东西,可以有多个按钮具有自己的叠加弹出窗口,并且在单击弹出窗口外部时它们应该关闭。现在我正在使用 TemplateRef (在我的情况下为#toggleButton) 打开它们,但它只在一个按钮上工作,即第一个按钮,它同时打开所有弹出窗口。任何帮助将不胜感激。
我正在附加 stackblitz 链接,https://stackblitz.com/edit/angular-d8tnwg?file=src/app/app.component.ts
HTML:
<ng-container>
<tr>
<td class="custom-td" style="overflow:visible;">
<button #toggleButton class="icon-info" (click)="showTooltip()"></button>
<div #menu class="overlay-text" [ngClass]="status ? 'open' : ''">
<p>This is a placeholder text and will be copied
if you click on button!</p>
<div class="form-group">
<input type="text">
<button class="icon-filecopy"></button>
</div>
</div>
</td>
</tr>
<tr>
<td class="custom-td" style="overflow:visible;">
<button #toggleButton class="icon-info" (click)="showTooltip()"></button>
<div #menu class="overlay-text" style="background-color: yellow" [ngClass]="status ? 'open' : ''">
<p>This is a placeholder text and will be copied
if you click on button!</p>
<div class="form-group">
<input type="text">
<button class="icon-filecopy"></button>
</div>
</div>
</td>
</tr>
<tr>
<td class="custom-td" style="overflow:visible;">
<button #toggleButton class="icon-info" (click)="showTooltip()"></button>
<div #menu class="overlay-text" style="background-color: red" [ngClass]="status ? 'open' : ''">
<p>This is a placeholder text and will be copied
if you click on button!</p>
<div class="form-group">
<input type="text">
<button class="icon-filecopy"></button>
</div>
</div>
</td>
</tr>
</ng-container>
TS:
status: boolean = false;
@ViewChild("toggleButton") toggleButton: QueryList<ElementRef>;
@ViewChild("menu") menu: QueryList<ElementRef>;
constructor(private renderer: Renderer2) {
this.renderer.listen("window", "click", (e: Event) => {
console.log("click outside");
if (
e.target !== this.toggleButton.nativeElement &&
e.target !== this.menu.nativeElement
) {
this.status = false;
}
});
}
showTooltip() {
this.status = !this.status;
}
}
【问题讨论】:
-
好吧,首先,我不会在构造函数中添加任何内容,您应该将所有内容移至 ngOnInit angular.io/api/core/OnInit。然后,如果您希望每个按钮打开不同的弹出窗口,则需要使它们唯一,如果您使用相同的标志来启用/禁用所有人,它将影响所有人。如果您不想创建单独的方法,请发送一个 ID,并仅切换受影响的...我希望这是有道理的
-
@rmjoia 如何使用唯一 ID 打开?抱歉,我问的是愚蠢的问题,这里相对较新
-
没有“愚蠢的问题”提问是健康的,学习的第一步是承认你不知道 :) 我发布了一个可能解决方案的答案,我希望它可以帮助你掌握窍门它并到达那里..最终你可能想检查这个免费的很棒的资源。 thinkster.io/topics/fundamentals-of-angular
-
我在点击外部时添加了第二次 StackBlitz 关闭,虽然可能需要一些调整.. 但我不能花更多时间在这上面,我认为这两个示例都提供了关于如何根据我的理解实现你正在寻找的东西
标签: angular typescript dom binding click