fnx
fnx

Reputation: 393

Keep detecting changes to an observable created from array

I have two components, one is a parent and the other is a child. I'm passing an array to the child using @Input, and I need to run a function inside the child component every time the array gets updated. I'm sure it can be done using observables but haven't been able to figure out how to do it. I can get the initial value of the array, but the subscription seems to close after one change.

Here is a link to StackBlitz demo: https://stackblitz.com/edit/angular-y8sren?file=app%2Fhello.component.ts

parent.component.ts

arr: any[] = [
  { title: 'Test 1', value: 'Foo' },
  { title: 'Test 2', value: 'Bar' }
];

generateArray() {
  const newArr = [];

  for (let i = 1; i <= 20; i++) {
    newArr.push({ title: 'Item '+ i, value: Math.floor(Math.random() * 123) });
  } 

  this.arr = newArr;
}

child.component.ts

@Input() arr: any[];

obsArr$: Observable<any[]>;
finalArr: any[] = [];

ngOnInit() {
  this.obsArr$ = Observable.from(this.arr);

  this.obsArr$
    .concatMap(val => Observable.of(val))
    .toArray()
    .subscribe(data => {
      // This needs to be run everytime arr changes to keep data in sync
      // But this gets run only once
      this.finalArr = data;
    },
    console.error
    );
}

Upvotes: 0

Views: 1089

Answers (1)

bugs
bugs

Reputation: 15323

No need to use Observables. Simply use ngOnChanges (Docs), which is called when any data-bound property of a directive changes.

Just import it import { OnChanges } from '@angular/core'; and use it like OnInit:

ngOnChanges() {
  // do what you want with the ()Input prop whenever the parent modifies it
}

Upvotes: 4

Related Questions