我有一些代码可以动态地向我的页面之一添加/删除组件。这似乎工作得很好,我的方法基于 Rob Wormald 的很棒的方法NG2 高级讲座 https://www.youtube.com/watch?v=ZqGvilzDbac.
以标准方式做事看起来像这样:
@Component({
template: `
<parent-component>
<template #dyn_target></template>
</parent-component>
`
})
export class MyComp {
@ViewChild('dyn_target', {read: ViewContainerRef}) myTarget;
constructor(protected cfr: ComponentFactoryResolver) {}
ngOnInit(): void {
const factory = this.cfr.resolveComponentFactory(DynComp);
const compRef = this.myTarget.createComponent(factory);
}
}
一切都很愉快并且顺利。但现在我的问题是,如果组件的目标位置是一个本身位于 *ngIf 内部的元素,我该如何做这样的事情?我有代码知道 *ngIf 何时应显示新元素,但我不知道如何在 *ngIf 内部查找 ViewContainerRef 目标。
@Component({
template: `
<parent-component>
<other-comp></other-comp>
<div *ngIf="showMe"
<nested-comp>
<template #dyn_target></template>
</nested-comp>
</div>
</parent-component>
`
})
export class MyComp {
@ViewChild('dyn_target', {read: ViewContainerRef}) myTarget;
showMe: boolean = false;
constructor(protected cfr: ComponentFactoryResolver) {}
addDynComponent(): void {
// Q: how do I do this? vv
const target: ViewContainerRef = lookup('dyn_target');
const factory = this.cfr.resolveComponentFactory(DynComp);
const compRef = target.createComponent(factory);
}
}
我考虑过尝试删除 ngIf 并使整个块动态化,但这并不适合我的情况,因为大多数内容是静态的,当/如果 ngIf 为 true 时,只需要添加一个子组件。
有人知道在 ngIf 将其他元素添加到 DOM 后如何动态查找 ViewContainerRef 吗?
注意:我想到的另一种方法是添加一个新的组件类型,该类型仅显示基于组件类类型的输入的嵌套组件。我见过为 Ionic 2 所做的此类事情,它可能对我的情况有效,但似乎有点矫枉过正。所以像这样:
@Component({
template: `
<parent-component>
<other-comp></other-comp>
<div *ngIf="showMe"
<nested-comp>
<show-comp [compClass]="dynClass"></show-comp>
</nested-comp>
</div>
</parent-component>
`
})
export class MyComp {
dynClass: any;
showMe: boolean = false;
addDynComponent(): void {
dynClass = DynComp;
}
}