我想知道如何知道绑定属性何时收到值,即使它是相同的值。
例如
这是一个功能组件
import {
Component,
OnInit,
Input,
OnChanges,
SimpleChanges
} from '@angular/core';
@Component({
selector: 'feature-component',
templateUrl: './template.html',
styleUrls: ['./style.sass']
})
export class FeatureComponent implements OnInit, Onchanges {
@Input() bondedProperty: any;
ngOnInit() {
}
ngOnChanges(simpleChanges: SimpleChanges) {
// not called inside the setInterval function
console.log('the bonded property received any value.');
}
}
应用的组件
import {
Component,
AfterViewInit
} from '@angular/core';
@Component({
selector: 'app-component',
templateUrl: './template.html',
styleUrls: ['./style.sass']
})
export class AppComponent implements AfterViewInit {
bondedProperty: any;
constructor() {
this.bondedProperty = 10;
}
ngAfterViewInit() {
const
interval = setInterval(
() => {
this.bondedProperty = 10;
console.log('function called after interval');
clearInterval(interval);
}, 5000
);
}
}
最后,应用程序的模板
<feature-component
[bondedProperty]="bondedProperty"
>
</feature-component>
问题是,如果在 中分配了相同的值bondedProperty
ngOnChanges
则不会调用,并且ngDoCheck
方法无法解决我的问题,因为我不知道"更改"是否在bondedProperty
中。
一种简单的方法,可以将bondedProperty
变量更改为对象。
以前:
this.bondedProperty = 10;
后:
this.bondedProperty = { 'value': 10 };
这样,如果更新事件中的值相同,更改检测将捕获更新事件。
堆栈闪电战演示
我所知,这不能用ngOnChanges
或@Input setters
来实现,因为 Angular 被设计为仅在值实际更改时调用ngOnChanges
或setter
。
即使它们与以前的值相同,您真正想要的可能是检测某种事件。您可以使用 RxJS BehaviorSubject
来实现这种目的。
功能组件
import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'feature-component',
template: 'property: {{ bondedProperty$ | async }}',
styleUrls: ['./style.sass']
})
export class FeatureComponent implements OnInit, Onchanges {
@Input() bondedProperty$: BehaviorSubject<any>;
ngOnInit() {
this.bondedProperty$.subscribe(value =>
console.log('the bonded property received any value.')
);
}
}
应用组件
import { Component, AfterViewInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-component',
template: '<feature-component [bondedProperty$]="bondedProperty$"></feature-component>',
styleUrls: ['./style.sass']
})
export class AppComponent implements AfterViewInit {
bondedProperty$ = new BehaviorSubject<any>(0);
constructor() {
this.bondedProperty$.next(10);
}
ngAfterViewInit() {
const
interval = setInterval(
() => {
this.bondedProperty$.next(10);
console.log('function called after interval');
clearInterval(interval);
}, 5000
);
}
}
https://stackblitz.com/edit/angular-so-54059234-eshtnr