简体   繁体   中英

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

Sample Component has data which array of object and it has child component on their array loop. Sample.component

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>

now I need to detect changes when any value on object is changed from parent

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>

I couldn't get the changes since the data is not an Input value. How to get changes in child? StackBlitz Note: This is only sample code, in realistic data has huge number arrays of object with multiple hierarchy.

Remove changeDetection: ChangeDetectionStrategy.OnPush from SamplechildComponent . Then it works fine. You should use default angular changeDetection system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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