My FormGroup is shown below:
this.productGroup = this.fb.group({
name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])],
desc: ['', Validators.maxLength(3000)],
category: ['', Validators.required]
variants: this.fb.array([
this.fb.group({
type: '',
options: ''
})
])
});
I am looking to dynamically add control fields for type
and options
when the user clicks on a button. The FormArray should have items like this after user input:
[ {type: 'size', options: 'Small', 'Big'}, {type: 'color', options: 'red', 'blue, 'yellow'}, ... ]
.
This is what I'm trying to achieve:
// Function to add new item to FormArray
addItem(): void {
this.variantsArray = this.productGroup.get('variants') as FormArray;
this.variantsArray.push(this.fb.group({
type: '',
options: ''
}));
}
// Template
<form [formGroup]="productGroup">
// inputs...
<div formArrayName="variants" *ngFor="let item of productGroup.controls['variants']; let i = index;">
<div [formGroupName]="i">
<div class="row">
<mat-form-field class="col-12">
<input formControlName="type">
</mat-form-field>
</div>
<div class="row">
<mat-form-field class="col-12">
<input formControlName="options">
</mat-form-field>
</div>
</div>
<div class="row">
<a href="javascript:" (click)="addItem()"> Add Variant </a>
<a href="javascript:" (click)="removeItem(i)" *ngIf="i > 0"> Remove Variant </a>
</div>
</div>
</form>
How can I get it to work?