<div class="container">
<form [formGroup]="keyValueForm" (ngSubmit)="doSubmit()">
<div class="form-row" formArrayName="details" *ngFor="let field of keyValueForm.get('details').controls; let ind = index;">
<ng-container [formGroupName]="ind">
<div class="form-group col-md-5">
<label>Key</label>
<input type="email" class="form-control" formControlName="key" placeholder="Key">
</div>
<div class="form-group col-md-5">
<label>Value</label>
<input type="text" class="form-control" formControlName="value" placeholder="Value">
</div>
<div class="form-group col-md-2" *ngIf="ind > 0">
<button class="btn btn-danger" (click)="removeRow(ind)" style="margin-top:30px;">Remove</button>
</div>
</ng-container>
</div>
</form>
<button class="btn btn-success" (click)="addRow()">Add Row</button>
</div>
<pre>
{{keyValueForm.value | json}}
</pre>
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public keyValueForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
const items = [];
items.push(this.formBuilder.group({
key: new FormControl(''),
value: new FormControl('')
}));
items.push(this.formBuilder.group({
key: new FormControl(''),
value: new FormControl('')
}));
this.keyValueForm = this.formBuilder.group({
details: this.formBuilder.array(items)
});
}
addRow() {
const details = this.keyValueForm.get('details') as FormArray;
details.push(this.createItem());
}
removeRow(index) {
const details = this.keyValueForm.get('details') as FormArray;
details.removeAt(index);
}
createItem(): FormGroup {
return this.formBuilder.group({
key: [],
value: []
});
}
}