【发布时间】: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