Using dynamic forms, I need to give users the ability to create form fields dynamically. There should be a "Add" button, and when the user clicks on this button, 4 input fields will be created.
I can create one field dynamically so far. Below is my code
In HTML, I use an index to create formControlName
<div class="row">
<div class="col-xs-12">
<div formArrayName="properties">
<button class="btn btn-default btn-xs" type="button" (click)="onAddProperty()">Add</button>
<div class="form-group" *ngFor="let propertyControl of searchForm.get('properties').controls; let i = index">
<input type="text" class="form-control" [formControlName]="i">
<!-- <input type="text" class="form-control" [formControlName]="'B'"+"i">
<input type="text" class="form-control" [formControlName]="'C'"+"i">
<input type="text" class="form-control" [formControlName]="'D'"+"i"> -->
</div>
</div>
</div>
</div>
and then in the component by clicking the control on the FormArray
searchForm: FormGroup;
onAddProperty() {
const control = new FormControl(null);
(<FormArray>this.searchForm.get('properties')).push(control);
}
Now I can click the "Add" button any number of times, and for each click one input field will be created.
4 . , ControlName. , , 1 , 4 .