Here is my FormGroup:
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 need to dinamically add type
and options
control fields after the user click on a button. FormArray should look like this after User Input:
[ {type: 'size', options: 'Small', 'Big'}, {type: 'color', options: 'red', 'blue, 'yellow'}, ... ]
.
Here whats I'm trying to do:
// 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()"> Adicionar Variante </a>
<a href="javascript:" (click)="removeItem(i)" *ngIf="i > 0"> Remover Variante </a>
</div>
</div>
</form>
How to make it work?