Angular:捕获动态容器内发出的事件
Angular: capture an event emmited inside a dynamic container
我不知道题名是否符合要求,但我正在尝试捕获动态组件发出的事件(点击)。我的目标是创建一个组件 onClick 并以相同的方式销毁它。我实际上设法做到了这一点,但是 parent(创建者和破坏者)组件中的两个按钮
parent 组件 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();
}
Parent 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>
我怎样才能完成这项工作?我怎样才能获得模板的引用,以便我可以告诉 parent 组件发射事件在这些标签内?
只需订阅EventEmitter
(继承Observable
):
this.componentRef.instance.closeList.subscribe(() => this.componentRef.destroy());
我不知道题名是否符合要求,但我正在尝试捕获动态组件发出的事件(点击)。我的目标是创建一个组件 onClick 并以相同的方式销毁它。我实际上设法做到了这一点,但是 parent(创建者和破坏者)组件中的两个按钮
parent 组件 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();
}
Parent 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>
我怎样才能完成这项工作?我怎样才能获得模板的引用,以便我可以告诉 parent 组件发射事件在这些标签内?
只需订阅EventEmitter
(继承Observable
):
this.componentRef.instance.closeList.subscribe(() => this.componentRef.destroy());