我有一个FormGroup汇率数组,即ratesMainArray
是@Input
,从父级到子级。每当父组件中其长度发生变化时,我就通过ngOnChanges
或special
键值在normal
中对其进行过滤,并将过滤后的数组的length
值存储在两个本地属性specialRates
和normalRates
的类型当然是number
。
我需要听听长度值的变化,但是ngOnChanges
仅对父数组的变化做出反应。
我已经开始使用ngDoCheck
来实际检测过滤后的数组值变化,但是当我尝试对过滤后的数组长度做出反应时,我收到了错误Error trying to diff '2'. Only maps and objects are allowed
。
这是代码的简化版本:
...
@Input() ratesMainArray: FormGroup[];
specialRates: number;
normalRates: number;
differ: any;
constructor(private differs: KeyValueDiffers) {
this.differ = differs.find({}).create();
}
ngDoCheck() {
const changes = this.differ.diff(this.specialRates);
if (changes) {
changes.forEachAddedItem(r => console.log('added ' + r.currentvalue));
}
}
async ngOnChanges(changes: SimpleChanges) {
if ((this.ratesMainArray && this.ratesMainArray.length)
&& (changes && changes.ratesMainArray && changes.ratesMainArray.currentvalue.length)) {
this.specialRates= this.ratesMainArray.filter(t => t.controls.isspecialRate.value === true).length;
this.normalRates= this.ratesMainArray.filter(t => t.controls.isspecialRate.value === false).length;
}
// ideally,I would like to do something like this:
// if (this.specialRates.valueChanges or changes.specialRates.currentvalue) {
// do somthing
// } else {
// do something else
// }
}
我不一定需要使用ngDoCheck
,但是由于它正在检测过滤后的数组更改,因此我认为这是必须的方法。为了清楚起见,在尝试private cd: ChangeDetectorRef
之前,我还尝试过使用this.cd.detectChanges();
和ngDoCheck
运气不好。
感谢您的帮助!