I am starting with Angular 2, I have a child component "ChildCmp" initialized and after I need destroy component through a click, let say:
@Component({
selector: 'main-cmp',
templateUrl: './main-cmp.html',
directives: [ChildCmp]
})
class MainCmp {
@ViewChild(ChildCmp)
childCmp: ChildCmp;
destroyChildClick(){
this.childCmp.destroy();
}
}
but the previous code doesn't run, destroy() is undefined and exception is:
TypeError: this.childCmp.destroy is not a function
I have read this thread and there are using ViewContainerRef.createComponent(), the component created with this is an instance of "ComponentRef", but the childCmp doesn't have "ComponentRef" implementation.
How I can implement or inject the destroy method?
Thanks for all!
Short answer
export class MainCmp {
@ViewChild(ChildCmp) childRef: ChildCmp;
destroyClick() {
this.childRef?.destroy();
}
}
I know the above code won't make sense in normal scenarios and I wouldn't use it, but since I don't have the context, I answered based on the given question. The parent should check if the child reference is defined first, then it can destroy the child.
Better way is using an NgIf
to destroy child component, but again I don't know the context or the use case.
@Component({
selector: 'main-cmp',
template: `
<child-cmp *ngIf="childDestroyed"></child-cmp>
<button (click)="childDestroyed = true">Destroy child</button>
`,
})
class MainCmp {
childDestroyed: boolean;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With