在Angular中,当使用响应式表单数组时,可以通过以下步骤来设置表单控件的值:
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
ReactiveFormsModule
]
})
export class AppModule { }
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-my-form',
template: `
`
})
export class MyFormComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
items: this.fb.array([ this.createItem() ])
});
}
get items() {
return this.myForm.get('items') as FormArray;
}
createItem() {
return this.fb.group({
name: ''
});
}
setValues() {
const values = [
{ name: 'Item 1' },
{ name: 'Item 2' },
{ name: 'Item 3' }
];
this.myForm.setControl('items', this.createItemsArray(values));
}
createItemsArray(items: any[]) {
const arr = this.fb.array([]);
items.forEach(item => {
arr.push(this.fb.group(item));
});
return arr;
}
}
setValues() {
const values = [
{ name: 'Item 1' },
{ name: 'Item 2' },
{ name: 'Item 3' }
];
this.myForm.setControl('items', this.createItemsArray(values));
}
以上代码示例演示了如何在Angular中使用响应式表单数组设置表单控件的值。请确保在使用这些代码示例之前已经正确导入所需的模块和类。