PatchValue or setValue with formGroup more formArray and formGroup
我有第二种形式。我需要使用来自银行的日期(json文件)填写字段。在
错误:
ERROR Error: Uncaught (in promise): TypeError: _this.form.controls.itens.value [i] .description.patchValue is not a function
我尝试使用以下表达式:
1 | this.form.controls.itens.value[i].description.patchValue(item.description); |
但是,我得到了上面提到的错误。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | generateFormGroup(): void { this.form = this._formBuilder.group({ id: [null], alias: ['Relat?3rio de Despesa', [Validators.required, Validators.maxLength(50)]], job: [null, [Validators.required]], customer: [{ value: null, disabled: true }, [Validators.required]], contact: [{ value: null, disabled: true }, [Validators.required]], currency: [{ value: 1, disabled: true }, [Validators.required]], exchangeRate: [{ value: null, disabled: true }], advanceValue: ['0'], itens: this._formBuilder.array([this.createItem()]), }); } createItem(): any { return this._formBuilder.group({ id: [null], product: [null, [Validators.required]], productIcon: [null], description: this._formBuilder.group({ descriptionProduct: [null], origin: [null], km: [null], destination: [null], rental: [null], days: [null], reason: [null], taglist: [null] }), date: [this.today, [Validators.required]], value: [0, [Validators.required, Validators.min(0.01)]], currency: [{ value: 1, disabled: true }, [Validators.required]], currencyAlias: [this.currency], receipt: [null], isLoading: [false], receiptId: [null], receiptExtension: [null], }); } populateFields(data: any): void { data.itens.forEach((item, i) => { this.form.controls.itens.value [i] .description.patchValue (item.description) // error } this.itens = data.itens; this.form.controls.itens.patchValue(data.itens); } |
更新:
我使用访问属性的方括号表示法来抑制类似
的错误
您可以在此Github页面上了解更多信息
仅当您具有多个级别的FormControl时,这才是一个问题。如果您有直接的建议,则可以使用
1 2 3 | this.form.controls.someControl.patchValue(someValue) this.form.get('someControl').patchValue(someValue) |
上面两个做同样的事情。如果它是一个简单的表单数组,则可以使用
将这些结合并进行某种类型转换,您可以执行以下操作
1 | ((this.form.get('controls') as FormArray).at(index) as FormGroup).get('description').patchValue(item.description); |
从理论上讲,上面的方法应该起作用:)
如果要从.ts文件中的formgroup访问field / formArray,则必须执行
我们使用['controls'],因为使用它可以到达formgroup及其formarray的特定字段,然后可以对其进行更新。