I have simple angular form to save user input. Where user can click on Add More button to add as many row they want which is working fine.
And I want that if testData (which defined on component) have length then this testData should be already in-place on component init, but I don't know how to do this.
component.ts
import { Component, VERSION, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
productForm: FormGroup;
testData = [{ "name": "test-1", "age": "24" }, { "name": "test-2", "age": "32" }, { "name": "Test-3", "age": "20" }]
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.addRowData();
this.productForm = this.fb.group({
stepName: 'Field Data',
fieldData: this.fb.array([]) ,
});
}
fieldData() : FormArray {
return this.productForm.get("fieldData") as FormArray
}
newFieldData(): FormGroup {
return this.fb.group({
name: '',
age: '',
})
}
addRowData() {
this.fieldData().push(this.newFieldData());
}
removeRowData(i:number) {
this.fieldData().removeAt(i);
}
onSubmit() {
console.log(this.productForm.value);
}
}
index.html
<table formArrayName="fieldData">
<tr *ngFor="let data of fieldData().controls; let i=index" [formGroupName]="i">
<td>
Name :
<input type="text" formControlName="name" class="form-control">
</td>
<td>
Age:
<input type="text" formControlName="age" class="form-control">
</td>
<td>
<button (click)="removeRowData(i)" class="btn btn-danger">Remove</button>
</td>
</tr>
<tr>
<th width="150px"><button type="button" (click)="addRowData()" class="btn btn-primary">Add More</button></th>
</tr>
</table>