繁体   English   中英

动态组件在 ViewInit 后加载时不起作用

[英]Dynamic Components not working when loaded after ViewInit

为什么下面的代码不起作用? 为什么@ViewChildren无法检测到ng-container

HTML

<div [innerHtml]="html"></div>

控制器:

import { Component, ViewChildren, AfterViewInit, QueryList,ViewContainerRef, ComponentFactoryResolver, Injector } from '@angular/core';

import { HelloComponent } from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  @ViewChildren('helloComponent',{read: ViewContainerRef}) components: QueryList<ViewContainerRef>

  html = "<ng-container #helloComponent></ng-container><ng-container #helloComponent></ng-container>";

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver, 
    private injector: Injector
  ){

  }

  ngAfterViewInit() {
     var i = 0;
     this.components.forEach(hello => {
       const componentFactory = this.componentFactoryResolver.resolveComponentFactory(HelloComponent);
       var componentRef = hello.createComponent(componentFactory);
       componentRef.instance.name = i.toString();
        i++;
     });

  }
}

这是演示: https : //stackblitz.com/edit/angular-8-dynamic-components-not-working

@ViewChildren 应该指的是其中有孩子的父母:

<ng-container #helloComponents>
  <ng-container>
  </ng-container>
  <ng-container>
  </ng-container>
  <ng-container>
  </ng-container>
</ng-container>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM