我已经定义了三个组件
PersonComponent
、AddressComponent
、CompanyComponent
。
当我知道组件名称为文本“
PersonComponent
”时,如何动态创建每个组件?
我以类似的方式注射了
ViewContainerRef
:
constructor(private viewContainerRef: ViewContainerRef) { }
在 ngOnInit 中时,我尝试创建一个类似的组件
const componentRef = this.viewContainerRef.createComponent(PersonComponent);
没关系。 但是,如果我想通过变量参数化这个函数,我该如何定义类型而不是这个组件呢?
这是一个简单的例子,我们将组件设置为值,键为字符串,这将帮助您实现动态渲染!
import { CommonModule } from '@angular/common';
import { Component, Type, ViewChild, ViewContainerRef } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { AComponent } from './a/a.component';
import { BComponent } from './b/b.component';
import { CComponent } from './c/c.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, FormsModule],
template: `
Current: {{property}}<br/>
<select [(ngModel)]="property">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select><br/>
<button (click)="add()">Toggle Component</button>
<div #container></div>
`,
})
export class App {
property: any = 'a';
componentMap: { [key: string]: Type<any> } = {
a: AComponent,
b: BComponent,
c: CComponent,
};
@ViewChild('container', { read: ViewContainerRef })
container!: ViewContainerRef;
private _counter = 1;
constructor() {}
add(): void {
this.container.clear();
// add the component to the view
const componentRef = this.container.createComponent(
this.componentMap[this.property]
);
// pass some data to the component
componentRef.instance.index = this._counter++;
}
}
bootstrapApplication(App);