Angular 11动态创建组件时ngOnInit失效、输入绑定及赋值优化问题
自定义动态组件加载指令实现
我编写了如下指令,用于向ng-container中添加动态组件,核心实现代码为:
@Directive({ selector: '[appAddingDirective]' }) export class AddingDirective { constructor(protected vc: ViewContainerRef) { } public addComponent(factory: ComponentFactory<any>, inputs: any): void { this.vc.clear(); const ref: ComponentRef<any> = this.vc.createComponent(factory); Object.assign(ref.instance, inputs); // 暂时没找到更优雅的输入属性赋值方式 ref.instance.ngOnInit(); // 关键注释:如果去掉这行调用,ngOnInit就不会触发 } }
指令的实际使用方式
该指令的使用代码如下:
@Component({ selector: 'app-wrapper', template: `<ng-container appAddingDirective></ng-container>` }) export class WrapperComponent implements AfterViewInit{ @ViewChild(DynamicItemDirective) private dynamicItem: DynamicItemDirective; constructor() { } ngAfterViewInit(): void { // 这里省略componentFactory的获取逻辑,不影响问题描述 this.dynamicItem.addComponent(componentFactory, {a: '123'}); } }
动态加载目标组件实现
被加载的目标组件代码如下:
@Component({ selector: 'app-dynamic', template: '<p>Dynamic load works {{ a }}</p>' }) export class DynamicComponent implements OnInit { @Input() a: string; constructor() {} ngOnInit(): void { console.log(this.a); debugger; } }
开发中遇到的具体问题
目前代码落地过程中碰到3个待解决的问题:
- 若移除
AddingDirective中ref.instance.ngOnInit()的手动调用,DynamicComponent的ngOnInit钩子就不会触发(在钩子里打的调试断点、console.log都不会执行)。需要明确:通过动态创建方式挂载的组件,是否支持Angular原生生命周期钩子?要如何调整才能让这些生命周期钩子按预期正常生效? - 目前即使通过
Object.assign给动态组件的@Input()属性a赋值为'123',组件模板中的插值{{ a }}也无法渲染出“Dynamic load works 123”的效果;但如果移除模板中的{{ a }},仅保留静态文本“Dynamic load works”时,文本可以正常渲染。需要定位该问题的产生原因,以及对应的修复方案。 - 相比当前使用
Object.assign(ref.instance, inputs)的赋值方式,是否存在更优雅、符合Angular设计规范的动态组件输入属性赋值方案?
补充说明:当前开发使用的Angular版本为11。
内容的提问来源于stack exchange,提问作者Eugeny89
相关产品推荐
相关产品推荐

