【问题标题】:Angular Dynamic Component isn't calling ngOnChangesAngular 动态组件不调用 ngOnChanges
【发布时间】:2023-02-22 11:55:28
【问题描述】:

(代码在 stackblitz 上:https://stackblitz.com/edit/angular-ivy-otin2c?file=src/app/app.component.tshttps://angular-ivy-otin2c.stackblitz.io

我在生产应用程序上使用 Angular 11,并且刚刚开始使用动态组件。我知道 Angular 14 中更新的 API,但还不能使用它们。

我使用的方法是从附加到 ng-template 的指令中检索到的 ViewContainerRef 上的 createComponent。看起来我可以设置任何输入,但如果组件依赖于执行类似 ngOnChanges 的操作,它就不会工作,因为它似乎没有被调用。事实上,似乎在动态组件上调用了所有其他生命周期方法。

      const factory = this.resolver.resolveComponentFactory(
        this.model.component
      );
      this.componentRef = this.target.container.createComponent(
        factory,
        0,
        this.injector,
        undefined,
        undefined
      );

      if (this.model.inputs) {
        for (const key of Object.getOwnPropertyNames(this.model.inputs)) {
          this.componentRef.instance[key] = this.model.inputs[key];
        }
      }

      this.componentRef.hostView.markForCheck();

我尝试使用其他方法来检测更改,但没有触发 ngOnChanges

如果我尝试使用this.componentRef.setInput(key, this.model.inputs[key]);,它将触发ngOnChanges,但我不能使用它。还有什么我可以添加来触发这个吗?

【问题讨论】:

    标签: angular dynamic components


    【解决方案1】:
    猜你喜欢
    • 2017-03-29
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2018-11-17
    • 1970-01-01
    • 2021-10-03
    • 2020-04-02
    相关资源
    最近更新 更多