如何在没有组件工厂的情况下销毁Angular 2组件?

如何在没有组件工厂的情况下销毁Angular 2组件?,angular,Angular,当通过ComponentFactory动态创建组件时,返回的ComponentRef提供了一种方法,该方法非常适合我想要完成的任务。考虑到这一点,看起来我所需要做的就是为静态创建的组件获取ComponentRef,然后使用其销毁函数(其中声明),但当我尝试此操作时,我得到一个错误,即“销毁不是函数”,即使我确实获得了一个对象 以下是我用于ViewChild的语法: @ViewChild(MyComponent) myComponentRef: ComponentRef<MyComponen

当通过ComponentFactory动态创建组件时,返回的ComponentRef提供了一种方法,该方法非常适合我想要完成的任务。考虑到这一点,看起来我所需要做的就是为静态创建的组件获取ComponentRef,然后使用其销毁函数(其中声明),但当我尝试此操作时,我得到一个错误,即“销毁不是函数”,即使我确实获得了一个对象

以下是我用于ViewChild的语法:

@ViewChild(MyComponent) myComponentRef: ComponentRef<MyComponent>;
在这里触发:

<button (click)="destroy()">Destroy</button>
销毁
调用此“destroy”方法适用于我动态创建的组件,而不是静态创建的组件

Edit:所以这似乎只是部分删除了组件,但没有从DOM中删除,这与在动态创建的组件上调用“destroy”时发生的行为不同。此外,当我单击试图销毁的组件时,我的click event函数仍然会启动

编辑2:我将ViewChild语法更新为显式读取ComponentRef,并返回“undefined”:

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

如果返回“undefined”,那么我猜这可能是不可能的。

您可以在组件的容器中添加*ngIf,并在基本条件(ngIf)中执行子元素的销毁和创建。例如:

他认为:

<div *ngIf="destroy">
    <component-child></component-child>
</div>
<button (click)="destroyFunction()">Click to Destroy</button>

执行这些步骤可以执行子元素的销毁。我希望它能有效地为您工作

您能使用*ngIf指令动态删除组件吗?这是Angular component lifecycle hooks页面@badger2013您使用了哪些资源来查找组件工厂的文档这在我身上是新的。使用我添加的*ngIf,而不是我创建的属性。我的ngIf在我的组件标签上,而不是div上。我的组件在mat选项卡中。切换选项卡时,我通过我的函数相应地设置ngIf。但是当回到标签页时,我可以看到以前的结果。看起来组件并不是这样被破坏的。
@ViewChild(MyComponent, {read: ComponentRef}) myComponentRef: ComponentRef<MyComponent>;
<div *ngIf="destroy">
    <component-child></component-child>
</div>
<button (click)="destroyFunction()">Click to Destroy</button>
//Declare the view child
@ViewChild(componentChild) componentChild: componentChild;

//Declare the destroy variable
destroy:boolean;

//Add a function to change the value of destroy (boolean)
public destroyFunction(){
    this.destroy = false;
}