使用FormArray时未在Reactive Form中获得正确的值

时间:2018-08-20 11:38:48

标签: javascript angular5 angular-reactive-forms

在运行时使用FormArray时未获得FormArray控制器的正确值

我的表单结构如下所示

    this.form = this.formBuilder.group({
        trips: this.formBuilder.array([]),
        carType: [null,Validators.required],
        carNo: [null,Validators.required],
        estimatedFuel: [0, [Validators.min(0)]],
        driver: [null,Validators.required]
    });

行程在添加后立即在运行时添加,然后在行程完成后,由于某些用户选择,我不得不用一些新字段替换表单控制器,如下所示:

在行程中添加首次访问

addTripGroup() {
    let tripLen = <FormGroup>this.form.controls['trips'].value.length;
    let obj: any = {};
    obj['tripType' + tripLen] = ["", Validators.required];
    let trip = <FormGroup>this.formBuilder.group(obj);
    (<FormArray>this.form.controls['trips']).push(trip);
}

在更新行程时

 replaceTripCtrl(index, tripType) {
    let obj: any = {};
    obj['tripType' + index] = [tripType, Validators.required];
    obj['tsno'] = [index + 1, Validators.required];
    obj['rUp'] = [null, Validators.required];
    obj['rUpNo'] = [null, Validators.required];
    obj['tround'] = [null, Validators.required];

    if (tripType == 'Single') {
        obj['rDown'] = [null, Validators.required];
        obj['rDownNo'] = [null, Validators.required];
    }
    let trip = <FormGroup>this.formBuilder.group(obj);

    //Replace a form group at a particular index
    <FormArray>this.form.controls['trips']['controls'].splice(index, 1, trip);

    console.log("on adding a trip---", this.form );
}

设置跳闸控制器值时

    populatedValue(value, key, index) {
      console.log("value key index", this.form);
    if (value) {
        <FormGroup>(<FormArray>this.form.controls['trips']).controls[index]['controls'][key].setValue(value.id);
    }
    else {
        <FormGroup>(<FormArray>this.form.controls['trips']).controls[index]['controls'][key].setValue(null);
    }
    console.log("value key index", this.form, this.form.controls['trips']['controls'][0].value);
}

我不明白为什么无论我是否通过使用this.form.value获得此值,this.form.controls ['trips'] ['controls'] [0] .value都会给出正确的行程值给我错误的值。有人可以帮忙吗?

0 个答案:

没有答案