简体   繁体   English

Angular NGRX / Reactive Form 和 ngOnChanges 时间问题

[英]Angular NGRX / Reactive Form and ngOnChanges timing issue

Angular 9 Angular 9

I'm trying to use ngOnchanges to trigger the load to my form.我正在尝试使用 ngOnchanges 来触发对我的表单的加载。 The data for the form is coming from an @input from the shell-component.表单的数据来自 shell 组件的 @input。

The problem I have is ngOnChanges is firing BEFORE ngOnit and the form has not been built yet for the data to populate.我遇到的问题是 ngOnChanges 在 ngOnit 之前触发,并且尚未构建表单以填充数据。

Playing around with it I have put in a temporary fix with a setTimeout, but its not ideal玩弄它我已经使用 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);
}

The timeout even with 0 delay is enough for the form to catch up.即使延迟为 0,超时也足以让表单赶上。 If I don't put in the delay the data is loaded before the form is built and triggers an error with no data.如果我不延迟数据在表单构建之前加载并触发没有数据的错误。

This seems pretty fundamental.这似乎很基本。 what I am missing?我错过了什么?

thanks.谢谢。

You can achieve it with a setter on the @Input() without needing ngOnChanges :您可以使用@Input()上的设置器来实现它,而无需ngOnChanges

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

You could use one of these very useful patterns described in answer below:您可以使用以下答案中描述的这些非常有用的模式之一:

how to stop ngOnChanges Called before ngOnInit() 如何停止在 ngOnInit() 之前调用的 ngOnChanges

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM