加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 在ngIf中动态添加组件

发布时间:2020-12-17 17:32:08 所属栏目:安全 来源:网络整理
导读:我有一些代码可以动态地添加/删除我的一个页面组件.这似乎工作得很好,我的方法基于Rob Wormald的真棒 Ng2 Advanced Talk. 以标准方式执行操作如下所示: @Component({ template: ` parent-component template #dyn_target/template /parent-component ` }) e
我有一些代码可以动态地添加/删除我的一个页面组件.这似乎工作得很好,我的方法基于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;
     }
 }

解决方法

我认为这应该有效

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读