私はそれに行を追加できる動的なテーブルを持っています。データをcol 3で動的に設定するにはどうすればよいですか?フォームビルダーを使用してフォームを作成していて、テーブルに行を動的に挿入するメソッドを持っています。私がcol1に何かを書くとき、私は変更して3列目に置くために2つの列の合計を計算するために購読します。Angular2/4 FormArrayフィールドに値を動的に設定する方法はありますか?
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を使用していますか? FormGroupを定義するコードをFormBuilderで提供することもできますか? – DeborahK
編集済み@DeborahK – jsd
どのようなエラーが表示されますか? –