【发布时间】:2017-12-14 23:49:28
【问题描述】:
我有一个可以向其中添加行的动态表。如何动态设置 col 3 中的数据?我正在使用表单生成器来创建我的表单,并且有一个方法可以接受在表中动态插入行。当我在 col1 中写一些东西时,我订阅更改并计算两个 col 的总和以将其放在第三个 col 上。
public sumRow() {
this.myForm
.get('rows')
.valueChanges
.subscribe((val) => {
// latest edit
val.foreach((item) => {
item.col3 = item.col1 + col2;
// But this one does not fill the col3 but
// it already giving the correct values
});
//loop to the val instead
// const ctrl = this.myForm.controls['rows'];
// ctrl.controls.forEach((field) => {
// const col1 = parseInt(field.get('col1').value, 10);
// const col2 = parseInt(field.get('col2').value, 10);
// const sum = col1 + col2;
// How to set these values to col3?
// Doesn't work: field.get('col3').setValue(sum);
});
}
public createForm() {
this.myForm = this.fb.group({
name: ['', Validators.required],
});
}
public pushRowItems(items) {
this.myForm.addControl('rows', this.fb.array([items]));
}
public initItemRows() {
return this.fb.group({
col1: 0,
col2: 0,
col3: 0,
});
}
public ngOnInit() {
this.createForm();
this.pushRowItems(this.initRowItems());
this.sumRow();
}
【问题讨论】:
-
您在使用 FormBuilder 吗?您能否提供使用 FormBuilder 定义您的 FormGroup 的代码?
-
编辑@DeborahK
-
你遇到了什么错误?