Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use ComponentRef to destroy my Component from within?

Tags:

angular

I want to be able to destroy my component from within itself. (Not from parent since it's dynamically created in multiple areas).

I've read from angular's api that they have a ComponentRef object. I've tried including it in the constructor but it says it needs an argument and I'm not sure what to pass to it.

Link: https://angular.io/api/core/ComponentRef

How can use ComponentRef in my component to destroy it?

import { Component, ComponentRef, OnInit } '@angular/core';
export class MyComponent implements OnInit {
    constructor(private ref: ComponentRef) {}

    ngOnInit() {
        this.ref.destroy()
    }
}
like image 264
Jonathan002 Avatar asked Aug 18 '17 13:08

Jonathan002


1 Answers

you can do it like this:


export class SelfDestroyableComponent implements OnInit {

    constructor(private host: ElementRef<HTMLElement>) {}

    // whatEver function name you want to give 
    selfDestroy() {
        this.host.nativeElement.remove();
    }

}

and call selfDestroy method whenever you want to destroy component

like image 168
babak.jalilian Avatar answered Oct 23 '22 14:10

babak.jalilian