I am currently working on a project where I require a material select box that allows for multiple values to be selected. These values are retrieved from an API that returns an array of objects. My goal is to generate a formarray of formgroups whenever a user selects a value from the select box.
For example:
The select box contains a list of categories, each represented by a category object. When a category is selected, I want the form to create a formarray consisting of the selected category object.
.html:
<div formArrayName="category">
<div *ngFor="let x of myForm.get('category')['controls'];let i = index">
<div [formGroupName]="i">
<mat-form-field appearance="outline">
<mat-label>Category</mat-label>
<mat-select [formControlName]="name" multiple>
<mat-option [value]="category.name"
*ngFor="let category of categories">
{{category.name}}
</mat-option>
</mat-select>
<!--
<mat-error *ngIf="myForm.controls.category.touched && myForm.controls.category.invalid">
<span *ngIf="myForm.controls.category.errors.required">Please select category</span>
</mat-error>-->
</mat-form-field>
</div>
</div>
</div>
.ts :
category:this.fb.array([this.fb.group({
"name":['']
})]),
When a value is selected, the current output looks like this
category: Array(1) 0: name: Array(2) 0: "Finance & Economics" 1: "Data Science"
However, I would like the output to be structured as follows:
category: Array(1) 0: name: Array(2) 0: "Finance & Economics" 1: name: Array(2) 0: "Data Science"
If anyone could assist me in resolving this issue, I would greatly appreciate it.