Javascript 角度:Ngonit钩子在动态创建的组件中不起作用
下面的指令将动态组件添加到ng容器中Javascript 角度:Ngonit钩子在动态创建的组件中不起作用,javascript,angular,Javascript,Angular,下面的指令将动态组件添加到ng容器中 @Directive({ selector: '[appAddingDirective]' }) export class AddingDirective { constructor(protected vc: ViewContainerRef) { } public addComponent(factory: ComponentFactory<any>, inputs: any): void { th
@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); // can't find more elegant way to assign inputs((
ref.instance.ngOnInit(); // IMPORTANT: if I remove this call ngOnInit will not be called
}
}
@指令({
选择器:“[appAddingDirective]”
})
导出类添加指令{
构造函数(受保护的vc:ViewContainerRef){}
公共addComponent(工厂:ComponentFactory,输入:任意):void{
this.vc.clear();
const ref:ComponentRef=this.vc.createComponent(工厂);
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 {
// hope it doesn't matter how we get componentFactory
this.dynamicItem.addComponent(componentFactory, {a: '123'});
}
}
@组件({
选择器:“应用程序包装器”,
模板:``
})
导出类包装器组件实现AfterViewInit{
@ViewChild(DynamicItemDirective)
私有dynamicItem:dynamicItem指令;
构造函数(){}
ngAfterViewInit():void{
//希望我们如何获得组件工厂并不重要
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;
}
}
@组件({
选择器:“应用程序动态”,
模板:“动态加载工作{{a}”
})
导出类DynamicComponent实现OnInit{
@Input()a:字符串;
构造函数(){}
ngOnInit():void{
console.log(this.a);
调试器;
}
}
以下是我的问题
ref.instance.ngOnInit()
调用AddingDirective
,我就不会进入DynamicComponent
的ngOnInit
(debugger
和console.log
不启动).组件生命周期挂钩是否在动态创建和连接的组件中工作?使这些挂钩工作的最佳方法是什么template:“Dynamic load works”
)中删除{{a}}
,Dynamic load works”,Dynamic load works
,我看不到呈现的字符串仍然可以工作123
。原因是什么,我如何修复Object.assign(ref.instance,inputs)
更好的方法来分配输入PS.我使用的是Angular 11我认为这个答案基本上涵盖了它->我认为这个答案基本上涵盖了它->