首页 文章

在ngIf中动态添加组件

提问于
浏览
4

我有一些代码可以动态地添加/删除我的一个页面组件 . 这似乎工作得很好,我的方法基于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 回答

  • 6

    我认为这应该有效

    @ViewChildren('dyn_target', {read: ViewContainerRef}) myTarget:QueryList<ViewContainerRef>;
    
    ngAfterViewInit() {
      this.myTarget.changes.subscribe(changes => {
        if(this.myTarget.toArray().length) {
          // myTarget ViewContainerRef available
        }
      });
    }
    

相关问题