在ngIf中动态添加组件

时间:2016-11-25 20:18:39

标签: angular

我有一些代码可以动态地将组件添加到我的某个页面中。这似乎工作得很好,我的方法基于Rob Wormald的真棒Ng2 Advanced Talk

以标准方式做事情如下:

@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是真的。

在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;
     }
 }

1 个答案:

答案 0 :(得分:6)

我认为这应该有用

@ViewChildren('dyn_target', {read: ViewContainerRef}) myTarget:QueryList<ViewContainerRef>;

ngAfterViewInit() {
  this.myTarget.changes.subscribe(changes => {
    if(this.myTarget.toArray().length) {
      // myTarget ViewContainerRef available
    }
  });
}
相关问题