我想知道绑定属性何时接收值,即使它是相同的值。
例如
这是一个功能组件
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
中有“更改”。
答案 0 :(得分:0)
据我所知,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.')
);
}
}
AppComponent
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
);
}
}
答案 1 :(得分:0)
将bondedProperty
变量更改为对象的一种简单方法。
之前:
this.bondedProperty = 10;
之后:
this.bondedProperty = { 'value': 10 };
这样,如果更改检测的值相同,则更改检测将捕获您的更新事件。