如何使close()动态?

时间:2019-06-07 12:16:37

标签: angular

   <div #child1> <button type="button" class="close" aria-label="Close" (click)="closing1()"></div>
    <div #child2>.<button type="button" class="close" aria-label="Close" (click)="closing2()">..</div>
    <div #child3>....</div>


    @ViewChild('child1') private child1: ElementRef;
    @ViewChild('child2') private child2: ElementRef;
    ...
    closing1() {
    this.child1.nativeElement.remove();

    }
    closing2() {
    this.child2.nativeElement.remove();
    }

如何仅使用1个close()方法优化上述代码?

2 个答案:

答案 0 :(得分:3)

最简单的方法是将元素ref传递给点击处理程序:

<div #child1>
   <button type="button" class="close" aria-label="Close" (click)="close(child1)">
</div>
<div #child2>
   <button type="button" class="close" aria-label="Close" (click)="close(child2)">
</div>
<div #child3>....</div>


close(elem: HTMLElement) {
  elem.remove();
}

答案 1 :(得分:0)

<div *ngFor="let child of [1, 2, 3]" #child> <button type="button" class="close" aria-label="Close" (click)="close(child)"></div>
close(child: HTMLDivElement) {
  child.remove();
}

您的TS中不需要任何参考。

See it in action

You can do as many children as you want to