正确地从 DOM 中删除角度组件

2024-01-31

我创建了一个芯片组件,它有一个删除按钮。单击此按钮后,我想从 DOM 中删除整个组件,包括它的包装 HTML 标记。

芯片组件.ts

@Component({
    selector: "app-chips",
    template: `<div class="close-btn" #myChips>My chips
                   <i class="fa fa-times" aria-hidden="true" (click)="remove(myChips)"></i>
               </div>`
})
export class ChipsComponent {
    public remove(self: HTMLElement): void {
        self.remove();
    }
}

应用程序组件.html

<app-chips></app-chips>
<app-chips></app-chips>
<app-chips></app-chips>

在页面上呈现如下:

<app-chips>
    <div class="close-btn" #myChips>My chips
        <i class="fa fa-times" aria-hidden="true" (click)="remove(myChips)"></i>
    </div>
</app-chips>

单击删除按钮后,它仅删除芯片,但<app-chips></app-chips>保留在 DOM 中。

如何删除整个组件?

客观的

I try to create chips component like this: enter image description here


老话题,但因为我很难尝试同样的......

遗憾的是,组件无法自动删除自身

所以我们有以下选择。

1: 视图容器引用 https://angular.io/api/core/ViewContainerRef

您可以使用以下命令生成您的组件componentFactoryResolver,将它们存储到一个数组中,然后使用这个数组来完全删除那些组件

<ng-template #chipsContainer></ng-template>
@ViewChild('chipsContainer', { read: ViewContainerRef, static: true })
chipsContainer: ViewContainerRef

loadedChips: any[] = []

addChip(attributes: any) {
  let componentFactory = this.componentFactoryResolver.resolveComponentFactory(
    AppChipsComponent,
  )
  let componentRef = this.componentLoaderContainer.createComponent(componentFactory)
  let ref: any = componentRef.instance
  ref.init(this.loadedChips.lenght) // Will be used to know which index should be removed

  this.loadedChips.push(componentRef)

  // Subscribing to the EventEmitter from the chip
  ref.emitDeletion
    .subscribe((index: number) => {
       this._removeChip(index)
    })
}

private _removeChip(index: number) {
  this.loadedChips[index].destroy()
  this.loadedChips.splice(index, 1)
}

那么,您还应该在芯片组件中添加什么

export class AppChipsComponent {
  private _index: number

  @Output() emitDeletion = new EventEmitter<boolean>()

  init(index: number) {
    this._index = index
  }

  remove() {
    this.emitDeletion.emit(this._index)
  }
}

2:Javascript

如果第一个例子看起来很复杂(确实如此,如果你想听听我的意见'^^)你可以简单地添加一个id到html或任何其他可以帮助您识别它的东西

然后,当点击remove()你可以得到它,并正确删除它。

<!-- You can use an *ngFor to make it simpler -->
<app-chips id="appChips-0" [id]="appChips-0"></app-chips>
<app-chips id="appChips-1" [id]="appChips-1"></app-chips>
<app-chips id="appChips-2" [id]="appChips-2"></app-chips>
export class AppChipsComponent {
  @Input() id!: string

  remove() {
    document.getElementById(this.id).remove()
  }
}

Voilà.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

正确地从 DOM 中删除角度组件 的相关文章

随机推荐