Reputation: 35
I'm a beginner at Angular 5 trying to add input fields dynamically to a table with a form array. I've used *ngFor inside the tr tag and the sample code is as follows:
HTML File:
<table class="table">
<thead>
<tr>
<th>F1</th>
<th>F2</th>
</tr>
</thead>
<form novalidate role="form" [formGroup]="caseinfo">
<div formArrayName="caseRows">
<tbody>
<tr *ngFor="let caserow of caseinfo.controls.caseRows.controls; let i=index" [formGroupName]="i" >
<td>
<div class="form-group">
<input type="text" class="form-control" formControlName="caselpn">
</div>
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="form-control" formControlName="casesku">
</div>
</td>
</tr>
</tbody>
</div>
</form>
</table>
TS File:
initFormCase()
{
this.caseinfo = this.fb.group({
caseRows: this.fb.array([this.initCaseRows()]) // here
});
}
initCaseRows() {
return this.fb.group({
caselpn:[null, Validators.compose([
Validators.required,
])],
casesku:[null, Validators.compose([
Validators.required,
])]
});
}
This is what my output looks like: https://i.sstatic.net/rd5A1.png
Expected output: Input field 1 under F1 column. and Input field 2 under F2 column.
Note: I tried replacing the ngFor inside the tbody too. No luck. Thanks in advance! Sorry, can't post images as I have low rep points.
Upvotes: 1
Views: 8747
Reputation: 7867
Your HTML structure is wrong, try to update it as below and check
<form novalidate role="form" [formGroup]="caseinfo">
<div formArrayName="caseRows">
<table class="table">
<thead>
<tr>
<th>F1</th>
<th>F2</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let caserow of caseinfo.controls.caseRows.controls; let i=index" [formGroupName]="i">
<td>
<div class="form-group">
<input type="text" class="form-control" formControlName="caselpn">
</div>
</td>
<td>
<div class="form-group">
<input type="text" class="form-control" formControlName="casesku">
</div>
</td>
</tr>
</tbody>
</table>
</div>
</form>
Upvotes: 3