首页 > 解决方案 > 动态组件在 ViewInit 后加载时不起作用

问题描述

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

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

标签: angulardynamic

解决方案


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

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

推荐阅读