0

我有一个 FormGroup 数组,即ratesMainArray@Input父组件到子组件。每次它在父组件中的长度发生变化时,我都会ngOnChanges通过它的special或键值对其进行过滤,并将过滤后的数组的值存储在两个本地属性中,这当然是 type 。我需要听那个长度值的变化,但只对父数组的变化做出反应。我已经开始使用实际检测过滤后的数组值变化的方法,但是当我尝试对过滤后的数组长度做出反应时收到错误消息。normallengthspecialRatesnormalRatesnumberngOnChangesngDoCheckError 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

谢谢你的帮助!!

4

1 回答 1

0

您可以使用“设置”来分析您在 @Input() 中收到的数据

specialRates: number;
normalRates: number;
differ: any;
private _ratesMainArray: FormGroup[];
get ratesMainArray(): FormGroup[] {
   return this._ratesMainArray;
}
@Input() set ratesMainArray(value: FormGroup[]){
    if(value) {
      this._ratesMainArray = value;
this.specialRates= this.ratesMainArray.filter(t => t.controls.isSpecialRate.value === true).length;
this.normalRates= this.ratesMainArray.filter(t => t.controls.isSpecialRate.value === false).length;
    }
}

constructor(private differs: KeyValueDiffers) {
   this.differ = differs.find({}).create();
}

这里有另一个在@Input() 中获取/设置的示例: Angular2 @Input to a property with get/set

于 2019-11-13T12:45:11.213 回答