Why doesn't the following code work? Why is @ViewChildren
not able to detect the ng-container
s?
HTML
<div [innerHtml]="html"></div>
Controller:
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++;
});
}
}
Here's the demo: https://stackblitz.com/edit/angular-8-dynamic-components-not-working
@ViewChildren should refer to a parent with children inside it :
<ng-container #helloComponents>
<ng-container>
</ng-container>
<ng-container>
</ng-container>
<ng-container>
</ng-container>
</ng-container>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.