在Angular 8中动态数组中使用Patch时,需要使用一个特殊的语法格式来解决此问题。以下是示例代码:
在HTML中:
在component.ts中:
import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms';
@Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { items = [ { name: 'item 1', value: 1 }, { name: 'item 2', value: 2 }, { name: 'item 3', value: 3 }, ];
form = new FormGroup({}); constructor() { this.items.forEach((item, i) => { const group = new FormGroup({ name: new FormControl(item.name), value: new FormControl(item.value) }); this.form.addControl('item ' + i, group); }); }
patchForm() { this.form.patchValue({ 'item 0': { name: 'new name' } }); } }
在这个示例中,我们使用了Angular 8中的FormBuilder来创建一个名为“form”的动态表单。然后我们循环遍历数组中的每个项目,为每个项目创建一个FormGroup,并使用FormBuilder将这个组添加到表单中。最后,我们使用PatchValue方法来更新表单中的表单控件。
这是解决Angular 8