Trying to create a dynamic row table with input fields in all cells. The loaded data is static, and I'm facing issues adding more data in the view. However, the functionality to add and delete rows is working fine. I have experimented with ngModel and value but couldn't get it to work.
app.component.html:
<table>
<thead>
<button (click)="onAddRow()" *ngIf="addForm.get('rows')">add row</button>
</thead>
<tbody>
<tr *ngFor="let row of addForm.get('rows')?.controls; let index = index;">
<td>
name : <input [formControl]="row.get('name')">
</td>
<td>
description : <input [formControl]="row.get('description')">
</td>
<td>
qty : <input [formControl]="row.get('qty')">
</td>
<td>
<button (click)="onRemoveRow(index)">Remove</button>
</td>
</tr>
</tbody>
</table>
app.component.ts:
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl, FormArray, NgForm } from '@angular/forms'
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
addForm: FormGroup;
rows: FormArray;
constructor(private fb: FormBuilder) {
this.addForm = this.fb.group({
items: [null, Validators.required],
items_value: ['no', Validators.required]
});
this.rows = this.fb.array([{
"name": "Test Item",
"description": "Dedsc",
"qty": "q23"
}]);
}
ngOnInit() {
this.addForm.get("items").valueChanges.subscribe(val => {
if (val === true) {
this.addForm.get("items_value").setValue("yes");
this.addForm.addControl('rows', this.rows);
}
if (val === false) {
this.addForm.get("items_value").setValue("no");
this.addForm.removeControl('rows');
}
});
}
onAddRow() {
this.rows.push(this.createItemFormGroup());
}
onRemoveRow(rowIndex:number){
this.rows.removeAt(rowIndex);
}
createItemFormGroup(): FormGroup {
return this.fb.group({
name: null,
description: null,
qty: null
});
}
}
My output: https://i.sstatic.net/Kt54S.png
Expected output: https://i.sstatic.net/ODqVy.png
Also sharing a Stackblitz Example for reference.