我从 Angular 2 开始,我有一个子组件“ChildCmp”已初始化,在我需要通过单击销毁组件后,假设:
@Component({
selector: 'main-cmp',
templateUrl: './main-cmp.html',
directives: [ChildCmp]
})
class MainCmp {
@ViewChild(ChildCmp)
childCmp: ChildCmp;
destroyChildClick(){
this.childCmp.destroy();
}
}
但是前面的代码没有运行,destroy() 是未定义的,异常是:
TypeError: this.childCmp.destroy is not a function
我已阅读 this thread并且有使用 ViewContainerRef.createComponent(),用它创建的组件是 “ComponentRef” 的实例,但是 childCmp 没有“ComponentRef”实现。
如何实现或注入(inject) destroy 方法?
谢谢大家!
最佳答案
简答
export class MainCmp {
@ViewChild(ChildCmp) childRef: ChildCmp;
destroyClick() {
this.childRef?.destroy();
}
}
我知道上面的代码在正常情况下没有意义,我不会使用它,但由于我没有上下文,我根据给定的问题进行了回答。 parent 应该先检查 child 引用是否被定义,然后它可以销毁 child 。
更好的方法是使用 NgIf
来销毁子组件,但同样我不知道上下文或用例。
@Component({
selector: 'main-cmp',
template: `
<child-cmp *ngIf="childDestroyed"></child-cmp>
<button (click)="childDestroyed = true">Destroy child</button>
`,
})
class MainCmp {
childDestroyed: boolean;
}
关于typescript - Angular 2 - 销毁子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38676997/