Angular: Binding Component Input to Property of Value from Observable

坚强是说给别人听的谎言 提交于 2019-12-24 19:56:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!