【问题标题】:Angular: capture an event emmited inside a dynamic containerAngular:捕获动态容器内发出的事件
【发布时间】:2020-06-05 14:48:36
【问题描述】:

我不知道问题的标题是否符合挑战,但我正在尝试捕获由动态组件发出的事件(点击)。我的目标是创建一个组件 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】:

    只需订阅EventEmitter(它继承Observable):

    this.componentRef.instance.closeList.subscribe(() => this.componentRef.destroy());
    

    【讨论】:

    • 好的,但是我是否在 closeList 方法中进行此订阅?
    • 不,你只是在这行this.componentRef.instance.listUsers = this.listUsers;之后实例化动态组件后才这样做@
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多