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

1.5k views Asked by At

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.

1

There are 1 answers

0
Ankur Mishra On BEST ANSWER

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