【问题标题】:ngOnChange only triggers after clicked somewhere on the screen after subscribengOnChange 仅在订阅后单击屏幕上某处后触发
【发布时间】:2021-08-26 17:30:33
【问题描述】:

我有以下组件。 家长:

@Component({
  selector: 'test'
})

onAccountChange(account: AccountItem): void {
  this.appService.callApi.subscribe((data) => {
    this.availableInstrument = data
  })
}

而我的 Child 组件如下:

@Component({
  selector: 'child'
})
export class Child implements OnInit, OnChanges {

  @Input('availableInstrument') availableInstrument!: any[]

  ngOnChanges() :void {
      console.log("Change")
      this.initializeComponent()
  }

我的问题是,我注意到 ngOnChange 函数只有在我单击屏幕上的其他位置后才会被调用,即使回调函数 (onAccountChange) 已经完成并且 availableInstrument 已经从 api 调用中填充。我希望在从 api 调用更改输入数据后立即调用 ngOnChange 函数,而不必单击屏幕上的其他位置。如果我在回调函数中对输入值进行硬编码,我会看到 ngOnChange 在子组件中被立即调用,但在它位于 subscribe 块内时却没有。

非常感谢!

【问题讨论】:

    标签: subscribe angular2-observables ngonchanges angular12


    【解决方案1】:

    您需要将变更检测策略设置为onPush

    @Component({
      selector: "child", 
     changeDetection: ChangeDetectionStrategy.OnPush
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-27
      • 2020-12-13
      • 2022-07-11
      相关资源
      最近更新 更多