I am looking to implement a feature where users can create multiple select dropdowns, choose options for each one, and then aggregate these selections into an array that will be sent to a parent component.
My current approach involves using an *ngFor loop to iterate over an array of strings (valueInputs) and dynamically creating a select dropdown for each element. By clicking an "add" button, a new empty string is added to the valueInputs array, allowing for more select dropdowns to be generated. Each select dropdown is bound to a specific index in the valueInputs array using ngModel.
You can view a demo of this functionality on Stackblitz: https://stackblitz.com/edit/angular-q5nwjq
Here is the code for the component:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
valueInputs = ['', '', ''];
}
And here is the template markup:
<ng-container *ngFor="let valueInput of valueInputs; let i = index">
<select
[(ngModel)]="valueInputs[i]">
<option value="" disabled>Select an option...</option>
<option value="opt1">Option 1</option>
<option value="opt2">Option 2</option>
</select>
</ng-container>
<div>
<button (click)="valueInputs.push('')">Add input</button>
<p>Value Inputs: {{ valueInputs | json }}</p>
</div>
The issue I am facing is that when I select an option in one dropdown, it affects the options in other dropdowns as well. The selected option changes, but the underlying valueInputs array remains unchanged.
This behavior is consistent across all select dropdowns. Changing one dropdown selection automatically updates the others. Is this a bug in Angular or is there a different approach I should consider implementing?