如何设置与角
问题描述:
我想设置值数组这样的数组形式值:如何设置与角
this.form.controls[name].setValue('name')
,但我与阵列的形式工作,而这是行不通的,即使我通过指数especific阵列形式
例如这是我的形式阵列和我想要做的是在一个功能
user: FormGroup;
users: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.user = this.buildGroup();
this.users = this.fb.group({
data: this.fb.array([this.user])
});
}
get fData() {
return this.users.get('data') as FormArray;
}
buildGroup() {
return this.fb.group({
name: ['', [Validators.required, Validators.minLength(2)]],
account: this.fb.group({
email: ['', Validators.required],
confirm: ['', Validators.required]
})
});
}
setValue(index) {
this.fData[index].controls[name].setValue('name')
}
onSubmit() {
this.fData.push(this.buildGroup());
const {valid, value} = this.fData;
console.log(valid, value);
}
但this.fData [指数] .controls [名称] .setValue('名称设定值')这不起作用
答
对于阵列,您需要使用setControl
。这样的事情:
this.productForm = this.fb.group({
productName: ['', [Validators.required,
Validators.minLength(3),
Validators.maxLength(50)]],
productCode: ['', Validators.required],
starRating: ['', NumberValidators.range(1, 5)],
tags: this.fb.array([]),
description: ''
});
...
// Update the data on the form
this.productForm.patchValue({
productName: this.product.productName,
productCode: this.product.productCode,
starRating: this.product.starRating,
description: this.product.description
});
this.productForm.setControl('tags', this.fb.array(this.product.tags || []));
答
这是我在formArray的特定窗体控件中手动设置了值,并为我工作。我有formArray
,命名为bundleDetails
。
this.formBuilderObj['bundleDetails'] =
this.formBuilder.array([this.createBundleItem()]);
createBundleItem(): FormGroup {
return this.formBuilder.group({
bsku: ['', Validators.required],
bqty: ['', Validators.required],
bprice: ['', Validators.required]
});
}
方法设置bsku控件的值(其中指数为[formGroupName]="i"
从HTML文件传递)。
setSku(sku: string, index: number) {
const faControl =
(<FormArray>this.pmForm.controls['bundleDetails']).at(index);
faControl['controls'].bsku.setValue(sku);
}
希望这会有所帮助。快乐的编码。
废弃我以前的答案。问题很可能是你[不向setValue传递一个数组](https://angular.io/api/forms/FormArray#example-1)。 – Tom
不应该将索引传递给具体的数组表单吗?我tryng这个,但这是不工作setValue(索引){ this.fData.setValue(['Name']); }错误说明必须为名称'name'提供一个fom控件的值 – LLaza
试试这个:this.fData [index] .controls ['name']。setValue(['name'])' – Tom