Angular NGRX / Reactive Form 和 ngOnChanges 计时问题

问题描述

角 9

我正在尝试使用 ngOnchanges 来触发对我的表单的加载。表单的数据来自 shell 组件的 @input。

我遇到的问题是 ngOnChanges 在 ngOnit 之前触发,并且尚未构建表单以填充数据。

玩弄它我已经使用 setTimeout 进行了临时修复,但它并不理想

ngOnChanges(changes: SimpleChanges): void {
 setTimeout(() => {
    // patch form with value from the store
    if (changes.profile) {
      const profile: IProfile = changes.profile.currentValue;
      this.displayProfile(profile);
    }
  },0);
}

即使有 0 延迟的超时也足以让表单赶上。如果我不延迟,则数据会在构建表单之前加载并触发没有数据的错误

这看起来很基本。我错过了什么?

谢谢。

解决方法

您可以使用 @Input() 上的 setter 实现它,而无需 ngOnChanges

@Input()
set profile(profile) {
  this.displayProfile(profile);
}
,

您可以使用以下回答中描述的这些非常有用的模式之一:

how to stop ngOnChanges Called before ngOnInit()