Angular 动态创建组件

有两种方式:视图动态渲染和组件动态创建(笔者拟自己拟的概念), 区别是前者的重心是使用 NgComponentOutlet 指令在视图模板中,后者的重心是使用 createComponent API 在组件内创建的

方式一:视图渲染

声明一个组件 app-dynamic

1
2
3
4
5
@Component({
selector: 'app-dynamic',
template: '<div> 123 <div>',
})
export class DynamicComponent implements OnInit {}

在其他组件的视图渲染该组件

1
2
3
4
5
6
7
8
9
@Component({
selector: 'my-app',
template: `
<ng-container *ngComponentOutlet="dynamicComponent"></ng-container>
`,
})
export class App {
dynamicComponent = DynamicComponent;
}

效果如下

image.png

传递参数

这种方式不能直接像 @Input() 一样去传值,但是 ngComponentOutlet 指令 **支持 injector 注入 token ** 的方式传值。

修改上述代码:

image.png

组件接收值

image.png

完整代码戳 这里

方式二:组件创建

声明一个组件

1
2
3
4
5
6
7
@Component({
selector: 'app-two',
template: '<div> {{ name }} </div>',
})
export class TwoComponent {
@Input() name: string;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Component({
selector: 'my-app',
template: `
<ng-template #container></ng-template>
`,
})
export class App {

constructor(
private environmentInjector: EnvironmentInjector,
private cdr: ChangeDetectorRef
) { }

ngAfterViewInit() {
const component = this.container.createComponent(TwoComponent, {
environmentInjector: this.environmentInjector,
});
// 传参
component.setInput('name', '组件动态创建');
this.cdr.detectChanges();
}
}

效果

image.png

参考资料