Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can component invoke a self destroy event

Tags:

I have a parent component which opens a new component on click of a link, this new component is supposed to have a close button which on close sends a closing message to parent and destroy itself.

We can send the closing message using ngOnDestroy method, but how do I invoke the destroying of the child component.

<parent>     <child></child> //child to be opened on click but close                      //event should be inside the child componenet </parent> 

Do correct me if i am having some conceptual mistake here. Thanks

like image 612
Sumit Agarwal Avatar asked Sep 29 '16 07:09

Sumit Agarwal


People also ask

How do you force ngOnDestroy?

To force a component to be destroyed, you use the HostListener from the Angular Core library. When using HostListener , you specify the event you want to listen to on the host of the component. In our case, we listen for the unloaded event so that when the page is unloaded, ngOnDestroy() will be triggered.

How do you destroy a child component?

1 suggested answer @Padrezz you just need to remove the component out of the rendered html and it will be automatically destroyed. To do this you would just use a blade @if conditional, to conditionally render the child component. Setting the condition to false, would then remove the component from the page.

How do you implement ngOnDestroy?

ngOnDestroy() gets called when a component is about to be destroyed. Notice how the example "destroys" the child component via the conditional ngIf='showChild'. By toggling the value of showChild, Angular creates and destroys the child component each time this value changes.

How do you unload components in angular 6?

because you want to unload the component, not merely hide it. export class ImageModalComponent implements OnInit { @Output() close = new EventEmitter(); public hideModal() { this. close. emit(); // here we tell the parent that the "close" button has been clicked. } }


2 Answers

If you add a component using ViewContainerRef.createComponent() like shown in Angular 2 dynamic tabs with user-click chosen components, then the component can destroy itself when you pass cmpRef to the created component.

Otherwise I don't think there is a way. You can pass a value to the parent so that an *ngIf removes the component.

<child *ngIf="showChild" (close)="showChild = false"></child> 
class ParentComponent {   showChild:boolean = true; } 
class ChildComponent {   @Output() close = new EventEmitter();    onClose() {     this.close.emit(null);   } } 
like image 63
Günter Zöchbauer Avatar answered Sep 20 '22 09:09

Günter Zöchbauer


Not sure about the cleanliness of such a solution, but I used:

this.viewContainerRef     .element     .nativeElement     .parentElement     .removeChild(this.viewContainerRef.element.nativeElement); 
like image 43
Sergiu Cosciug Avatar answered Sep 18 '22 09:09

Sergiu Cosciug