How do you destroy an Angular 2 component without a ComponentFactory?

Discussão em 'Angular' iniciado por badger2013, Setembro 11, 2024.

  1. badger2013

    badger2013 Guest

    When creating components dynamically through a ComponentFactory the ComponentRef that's returned provides a destroy method which works perfectly for what I'd like to accomplish. With that in mind, it looks like all I need to do is a get a ComponentRef for a statically created component and then use its destroy function (which this answer states), but when I try this I get an error saying that "destroy is not a function" even though I do get an object back.

    Here's the syntax I'm using for ViewChild:

    @ViewChild(MyComponent) myComponentRef: ComponentRef<MyComponent>;


    And my "destroy" call:

    private destroy() {
    this.myComponentRef.destroy();
    }


    Which is triggered here:

    <button (click)="destroy()">Destroy</button>


    Calling this "destroy" method works for components that I create dynamically, but not statically.

    Edit: So it seems like this does partially remove the component, but not from the DOM, which is not the same behavior that occurs when calling "destroy" on a dynamically created component. Additionally, my click event function still fires when I click on a component that I've tried to destroy.

    Edit 2: I updated my ViewChild syntax to explicitly read for a ComponentRef and I get "undefined" back:

    @ViewChild(MyComponent, {read: ComponentRef}) myComponentRef: ComponentRef<MyComponent>;


    If that returns "undefined" then I'm guessing this may not be possible.

    Continue reading...

Compartilhe esta Página