在动态组件加载的情况下,是否预期行为不会调用ngOnChanges生命周期钩子?只为我调用构造函数ngOnInit和ngAfterViewInit.但是根据文档,它应该在ngOnInit之前调用.
我正在加载这样的组件:
@ViewChild('place', { read: ViewContainerRef }) container: ViewContainerRef;
private componentRef: ComponentRef<MyLoggerComponent>;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
ngAfterViewInit() {
const componentFactory: ComponentFactory<any> = this.componentFactoryResolver.resolveComponentFactory(MyLoggerComponent);
this.componentRef = this.container.createComponent(componentFactory);
this.componentRef.changeDetectorRef.detectChanges();
}
Run Code Online (Sandbox Code Playgroud)
Sir*_*tek 10
根据讨论https://github.com/angular/angular/issues/8903动态组件加载ngOnChanges即使在调用后也不应在子组件中触发,detectChanges因为此事件仅保留用于模板绑定.
如果您的子组件仅以动态方式加载,则可以使用Javascript setter而不是ngOnChanges.这是一个例子:
export class DynamicallyLoadedComponent {
private _property: string;
get property(): string { return this._property; }
set property(newVal: string) {
if (this._property === newVal) { return; }
this._property = newVal;
this.onChanges(); // instead of ngOnChanges
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3466 次 |
| 最近记录: |