gpt4 book ai didi

angular - 如何在 Angular 5 中将 FormControl 动态添加到 FormGroup?

转载 作者:太空狗 更新时间:2023-10-29 18:19:07 26 4
gpt4 key购买 nike

我正在尝试构建与 FormGroup 和 FormArray 兼容的数据表。我将使用 parentForm 组将标题详细信息和行传递给此组件。

我创建了一个小的添加按钮,点击它,我将动态添加新项目。在这种情况下,UI 可以正常更新,但如果我打印 formGroup.value(),我只会得到传递的初始值。不是更新的 formControl。我不确定我错过了什么。

export class FormTableComponent implements OnChanges {
@Input() headers: Array<string>;
@Input() rows: Array<any>;
@Input() parentFG: FormGroup;
@Input() entriesName: string;

get entries(): FormArray {
return <FormArray>this.parentFG.get(this.entriesName);
}

constructor(private fb: FormBuilder, private cd: ChangeDetectorRef) {}

ngOnChanges() {
this.createFormControls();
}

createFormControls() {
this.parentFG.controls[this.entriesName] = this.fb.array([]);
this.rows.forEach(row => {
this.entries.controls.push(this.fb.group(row));
});
}
}

DEMO

最佳答案

您有几个问题:1. 将新行推送到 FormArray 本身以外的 FormArray 控件

this.entries.controls.push(this.fb.group(row));

应该是

this.entries.push(this.fb.group(row));

2。不要每次都创建新的 FormArray 并在调用 createFormControls() 时重新加载每一行,您可以通过 get entries() 方法访问它

解决方案一:

检查 entries 的长度,如果为 0,则用 rows 初始化它,否则将最后一行插入现有的 FormArray

createFormControls() {
const keys = Object.keys(this.entries.value);
if( keys.length === 0) {
this.rows.forEach(row => {
this.entries.push(this.fb.group(row));
});
} else {
const row = this.rows[this.rows.length - 1];
this.entries.push(this.fb.group(row));
}
}

解决方案 2:

就个人而言,我更喜欢将 createFormArray()appendTo()popFrom() 放入父组件中。它干净且易于阅读。在这种情况下,我们不需要 ChangeDetectionRef

我已将 createFormControls()form-table 组件移至 dummy 组件并将其重命名为 createFormArray() 并稍微更改了 addNewRow(),现在一切正常

// create FormArray once
createFormArray() {
const elements: any[] =[];

this.rows.forEach(row => {
elements.push(this.fb.group(row));
});
return this.fb.array(elements);
}

addNewRow() {
const newRow = {
name: 'NAFFD',
age: 12,
place: 'TN'
};

this.rows.push(newRow); // update rows

const persons = this.dummyForm.get('persons') as FormArray;
persons.push(this.fb.group(newRow)); // update FormArray
}

初始化虚拟表单时,请执行以下操作:

   this.dummyForm = this.fb.group({
persons: this.createFormArray(),
store: this.fb.group({
branch: '',
code: ''
})
});

enter image description here

希望对您有所帮助,祝您编码愉快!

关于angular - 如何在 Angular 5 中将 FormControl 动态添加到 FormGroup?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48833791/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com