【问题标题】:Angular NGRX / Reactive Form and ngOnChanges timing issueAngular NGRX / Reactive Form 和 ngOnChanges 时间问题
【发布时间】:2021-08-07 10:24:59
【问题描述】:

角度 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,超时也足以让表单赶上。如果我不延迟数据在表单构建之前加载并触发没有数据的错误。

这似乎很基本。我错过了什么?

谢谢。

【问题讨论】:

  • 为什么需要ngOnChanges?输入值是否来自商店?
  • 是的,ngOnChanges 可以方便地处理任何状态的变化回到表单。

标签: angular ngrx ngonchanges


【解决方案1】:

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

how to stop ngOnChanges Called before ngOnInit()

【讨论】:

  • 布尔解决方案对我不起作用。带有 isFirstChange 的 SimpleChanges 也可以。坦率地设置一个 SetTimeout 比一个新主题的麻烦更干净。
  • 嗯...试试其他的,尤其是:SimpleChanges API 之一:!changes["bar"].isFirstChange()
  • 我的意思是这是非常基本的,但它需要摆弄。我浏览了文档,找不到统一的方法。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2020-04-07
    • 1970-01-01
    • 2020-08-07
    • 2019-12-26
    • 2018-06-10
    • 2018-06-26
    • 1970-01-01
    • 2022-01-03
    • 2019-04-07
    相关资源
    最近更新 更多