Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - destroy child component

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!

like image 668
lextract Avatar asked Jul 30 '16 18:07

lextract


1 Answers

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;
}
like image 62
Murhaf Sousli Avatar answered Sep 29 '22 20:09

Murhaf Sousli