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>

最新更新