簡體   English   中英

Angular 如何通過以下方式檢測從父母到孩子的變化

[英]Angular how to detect changes from parent to child in the following way

示例組件的數據為 object 數組,並且其數組循環中有子組件。 樣本.組件

export class SampleComponent implements OnInit {
  data = [{ value: 3 }, { value: 1 }];
  constructor() {}

  ngOnInit(): void {}
  valueChange() {
    this.data[1].value = 5;
    this.data = [...this.data];
  }
  whenComponentRerendered() {
    console.log('Parent component rerendered');
  }
  consoleOutput() {
    console.log('Console from button click');
  }
}
<button (click)="valueChange()">
  Change input to 5
</button>
<ng-container *ngFor="let item of data">
  <app-samplechild [data]="item"></app-samplechild>
</ng-container>

現在我需要檢測 object 上的任何值從父級更改時的更改

export class SamplechildComponent implements OnInit {
  @Input('data') data!: any;
  constructor() {}

  ngOnInit(): void {}
  whenComponentRerendered() {
    console.log('child component rerendered');
  }
  changeValue() {
    this.data.value = 5;
  }
}
<p>
  The value from parent is
  {{ data | json }}
</p>

我無法獲得更改,因為數據不是輸入值。 如何獲得孩子的變化? StackBlitz注意:這只是示例代碼,在現實數據中有大量 arrays 的 object 具有多個層次結構。

從 SamplechildComponent 中移除changeDetection: ChangeDetectionStrategy.OnPush SamplechildComponent 然后它工作正常。 您應該使用默認的 angular changeDetection系統。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM