在Angular中,如果要更改表单数组的值,需要进行一些额外的步骤。以下是一个解决方法的代码示例:
在组件的HTML文件中,创建一个表单数组,并使用ngFor指令来循环显示表单控件:
在组件的TS文件中,初始化表单和表单数组,并编写一个方法来更改表单数组的值:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
myArray: this.fb.array([])
});
// 添加三个控件到表单数组
for (let i = 0; i < 3; i++) {
this.myArray.push(this.createItem());
}
}
get myArray() {
return this.myForm.get('myArray') as FormArray;
}
createItem() {
return this.fb.group({
name: ''
});
}
changeValues() {
// 更改表单数组的值
this.myArray.controls.forEach((control, index) => {
control.patchValue({ name: 'New Value ' + index });
});
}
}
在以上代码中,通过调用this.myArray.push(this.createItem())
将控件添加到表单数组中,并通过control.patchValue()
方法来更改表单数组的值。
最后,在按钮的点击事件中调用changeValues()
方法来触发更改操作。
通过以上步骤,就可以在Angular中成功更改表单数组的值。