我有两个组件,一个是父母,另一个是孩子。我正在使用@Input将数组传递给子节点,每次数组更新时我都需要在子组件内运行一个函数。我确信它可以使用observable来完成,但却无法弄清楚如何去做。我可以获得数组的初始值,但订阅似乎在一次更改后关闭。
这是StackBlitz演示的链接: 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
);
}
答案 0 :(得分:4)
无需使用Observables。只需使用ngOnChanges
(Docs),当指令的任何数据绑定属性发生更改时,就会调用它。
只需将其导入import { OnChanges } from '@angular/core';
并像OnInit
一样使用
ngOnChanges() {
// do what you want with the ()Input prop whenever the parent modifies it
}