【问题标题】:Angular 2 Dynamic Component loading ngOnChanges lifecycle hook callAngular 2 动态组件加载 ngOnChanges 生命周期钩子调用
【发布时间】:2017-03-29 09:36:16
【问题描述】:

在动态组件加载的情况下不调用 ngOnChanges 生命周期钩子是预期的行为吗? 只为我调用了构造函数 ngOnInit 和 ngAfterViewInit。但是根据docs 应该在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();
   }

Plunker

【问题讨论】:

标签: angular


【解决方案1】:

根据讨论,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
  }
}

【讨论】:

  • 想知道为什么他们限制使用ngOnChanges 绑定进行模板绑定。
  • @sirwojtek 你有可以工作的示例代码吗?
  • @SirWojtek 在这个例子中你使用的是什么版本的角度?
  • @Rich 它正在使用 5.2.4 版本(可能更早)
  • @aguetat 解决方案来自我公司代码,将尝试提取 Plunker
猜你喜欢
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 2016-12-13
  • 1970-01-01
  • 2017-09-16
  • 2018-04-16
  • 2017-01-18
  • 2017-11-13
相关资源
最近更新 更多