I had to make a component that dynamically creates mat-selects when clicking a add button. The point is that the user can select a value from each mat-select and then everything gets sent to the parent component with an output.
This is the logic that I used
The component starts with a array of strings with only one element:
export class DynamicMatSelectComponent {
matSelects: string[] = [""];
}
In the template I have this:
<div *ngFor="let matSelect of matSelects; let i = index">
<mat-select [(ngModel)]="matSelects[i]" (selectionChange)="onSelectionChange(i, $event)"
// mat options
</mat-select>
</div>
I then have a button that when clicked simply adds a empty string to the matSelects array so that the ngFor makes more of mat-select.
The problem is that when I create multiple mat-selects and I choose a option for, let's say, the first one, the second one also gets updated with the same value as the first one.
I really don't know how to get around this because I haven't found a clear way to make sure that I'm targeting only a specific mat-select. I believe the problem has something to do with the fact that I'm making stuff up at runtime and maybe I'm not following the correct methodology.
It seems that the answer was easier than I thought. Basically instead of having a array of string, I made an array of objects like this:
matSelects: any[] = [{ value: "" }];and each time I click the add button I do this:this.matSelects.push({ value: "" });. Now it looks like it always targets the right mat-select, maybe it has something to do with the reference of objects