声明式方法
您可以使用ngComponentOutlet。
代码:
shapes: ShapeComponent[] = [CircleComponent, SquareComponent];
模板:
<ng-container *ngFor="let shape of shapes">
<ng-container *ngComponentOutlet="shape">
</ng-container>
</ng-container>
ngComponentOutlet - 实例化单个 Component 类型并插入
将其主机视图转换为当前视图。 NgComponentOutlet 提供了一个
动态组件创建的声明式方法。
NgComponentOutlet 需要一个组件类型,如果设置了一个假值
视图将被清除,任何现有组件都将被销毁。
因此,模板中不需要硬代码。 *ngFor 将遍历代码中的组件类型数组
更新
不记得给AppModule的entryComponents添加动态渲染组件:
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent, AComponent, BComponent ],
entryComponents: [
AComponent, BComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
StackBlitz Demo
设置数据的命令式方法
app-component.template:
<ng-container #comps>
</ng-container>
通过ViewChild 装饰器访问#comps(ng-container) 视图并创建组件。
所以你不能初始化像b = new BComponent() 这样的组件。
- 首先需要解析组件工厂。
- 通过viewContainerRef'screateComponent方法初始化组件。它将reference返回给实例化的组件
- 通过引用,访问实例属性并根据需要更新任何数据
app-component.ts:
@ViewChild('comps', { read: ViewContainerRef }) comps: ViewContainerRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
}
ngOnInit() {
this.comps.clear();
let aComponentFactory = this.componentFactoryResolver.resolveComponentFactory(this.compArr[0]);
let aComponentRef = this.comps.createComponent(aComponentFactory);
(<AComponent>aComponentRef.instance).name = 'A name';
let bComponentFactory = this.componentFactoryResolver.resolveComponentFactory(this.compArr[1]);
let bComponentRef = this.comps.createComponent(bComponentFactory);
(<BComponent>bComponentRef.instance).name = 'B name';
}
StackBlitzh Demo