在Angular中使用patchValue()
方法嵌套数组,可以按照以下步骤进行操作:
formGroup
:import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
formGroup: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.formGroup = this.formBuilder.group({
nestedArray: this.formBuilder.array([
this.formBuilder.group({
item: ['']
})
])
});
}
patchNestedArray() {
const nestedArray = this.formGroup.get('nestedArray') as FormArray;
nestedArray.patchValue([{ item: 'Value 1' }, { item: 'Value 2' }]);
}
}
formGroup
和formArrayName
来显示和编辑嵌套数组的值:
在上述示例中,我们创建了一个名为formGroup
的表单控件,其中包含一个名为nestedArray
的嵌套数组。然后,我们使用formArrayName
和formGroupName
在模板中显示和编辑嵌套数组的值。
在patchNestedArray()
方法中,我们获取nestedArray
的控件,并使用patchValue()
方法将新的值分配给嵌套数组的每个项。