问题
In Angular 7, when the property of a value emitted by an Observable
is bound to the input of a child component, is it expected that the input value gets updated (and ngOnChanges
invoked) even when the bound property has not changed?
Given the following observable that simply emits a new object with identical properties every second:
const source$ = interval(1000).pipe(map(() => ({
prop: 'something'
})));
this.obs$ = source$;
Then bind a property of the emitted value to a child component:
<test-comp [something]="(obs$ | async)?.prop"></test-comp>
What I observe is that the 'something' setter and ngOnChanges
of test-comp
get invoked.
Also, comparing current and previous values are checked in ngOnChanges
shows they are identify equal:
if(changes['something'].currentValue === changes['something'].previousValue) {
console.log('They are equal');
}
Using a separate observable that simply maps the property from the source observable like so:
this.obs2$ = source$.pipe(map(v => v.prop));
<test-comp [something]="(obs$ | async)"></test-comp>
Works as I had expected, with the 'something' value not being set and ngOnChanges
not being called.
Here is a Stackblitz sample that shows the behaviour in question:
- Editor URL: https://stackblitz.com/edit/angular-wch28k
- App URL: https://angular-wch28k.stackblitz.io
Using Angular 7.2.1
Perhaps I've just got it completely wrong, but the behaviour seems inconsistent
来源:https://stackoverflow.com/questions/56569610/angular-binding-component-input-to-property-of-value-from-observable