Reputation: 1087
I don't know if the title of the question is up to the challenge, but I'm trying to capture an event(click) issued by a dynamic component. My goal is to create a component onClick and destroy it by the same means. I actually manage to accomplish that, but with both buttons in the parent (creator and destroyer) component
The parent component 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>
Dynamic 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();
}
}
Dynamic 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>
How can I make this work? How can I get the reference of the template so I can tell parent component the emmited event is inside those tags?
Upvotes: 1
Views: 479
Reputation: 31805
Just subscribe to the EventEmitter
(it inherits Observable
):
this.componentRef.instance.closeList.subscribe(() => this.componentRef.destroy());
Upvotes: 3