Angular:捕获在动态容器内发出的事件

问题描述 投票:0回答:1

我不知道问题的标题是否适合挑战,但我试图捕获由动态组件发出的事件(点击)。我的目标是创建组件onClick并通过相同的方法销毁它。我实际上设法做到了这一点,但是在父组件(创建者和销毁者)组件中同时使用了两个按钮

父组件TS:

listUsers: User;
 @ViewChild('listUsers',{read: ViewContainerRef, static:false}) usersContainer;
 componentRef: ComponentRef<any>;


createComponent(){
    this.usersContainer.clear();
    const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(DynamicComponent);
    this.componentRef = this.usersContainer.createComponent(factory);
    this.componentRef.instance.listUsers = this.listUsers;
  }

  closeList(event){
      console.log(event)  //  this.componentRef.destroy();
  }

父HTML

<button class="btn btn-primary" (click)="createComponent()">List users</button>

<template #listUsers>
    <app-dynamic (closeList)="closeList($event)"></app-dynamic>

</template>

动态TS:

export class DynamicComponent implements OnInit {
  @Input() listUsers: User;
  @Output() closeList = new EventEmitter<any>()
  constructor() { }

  ngOnInit(): void {
    console.log(this.listUsers)
  }
  close() {
    this.closeList.emit();
  }
}

动态HTML

<div class="container">
    <div class="row">
        <div class="col md-6 offset-md-3">
            <ul class="list-group" *ngFor="let u of listUsers">
                <li class="list-group-item">
                    {{u.username}}
                </li>
            </ul>
            <button class="btn btn-primary" (click)="close()">Close</button>
        </div>
    </div>
</div>

我该如何进行这项工作?我如何获得模板的引用,以便可以告诉父组件所包含的事件在这些标签内?

angular eventemitter angular-dynamic-components
1个回答
0
投票

仅订阅EventEmitter(它继承了Observable):

this.componentRef.instance.closeList.subscribe(() => this.componentRef.destroy());
© www.soinside.com 2019 - 2024. All rights reserved.