In my Angular 5 project, I am attempting to create a set of three <select>
elements using *ngFor. I came across a helpful thread on Stack Overflow that provided some guidance (check it out here). However, I've encountered an issue where the select elements are not independent - changing one affects the others, except for the third one. This is likely due to all selects sharing the same list of options. While this behavior makes sense, I want each select to be completely separate.
Below is the code snippet for looping through the 3 select elements with *ngFor:
<div class="col-sm-3" *ngFor="let groupField of selectedGroupingFields; let i = index;">
<select class="form-control col-sm-6" name="groupField{{i}}" [(ngModel)]="selectedGroupingFields[i]" (ngModelChange)="groupByFieldName($event, i)">
<option value=""></option>
<option [ngValue]="field.id" *ngFor="let field of columnDefinitions">{{field.name}}</option>
</select>
The collections used in this scenario are structured as follows:
selectedGroupingFields: string[] = ['', '', ''];
columnDefinitions = [
{ id: 'title', name: 'Title'},
{ id: 'duration', name: 'Duration'},
{ id: 'percentComplete', name: '% Complete'},
{ id: 'start', name: 'Start'},
{ id: 'Finish', name: 'Finish'},
{ id: 'cost', name: 'Cost'},
{ id: 'effortDriven', name: 'Effort-Driven'}
];
To demonstrate the problem, I have created a function that changes the first select element when a button is clicked:
changeFirstGroupBy() {
this.selectedGroupingFields[0] = 'title';
}
When executing this function, both the first and second select elements are affected. Curious about this unexpected behavior, I decided to manually create each select element in the HTML without using ngFor:
// Code example showing manual creation of individual select elements goes here...
Surprisingly, creating the select elements individually worked as intended, despite being structurally similar to the looped version. Moreover, changes made to the last select element also unexpectedly impact the second select. The mystery deepens...
If curious, check out this animated GIF depicting the issue: https://i.sstatic.net/TPAOD.gif
EDIT
I attempted switching from two-way binding to one-way binding but observed no change in behavior (
[ngModel]="selectedGroupingFields[i]"
).
ANSWERED
Update: The solution described above has been successfully implemented in one of my Open Source projects, Angular-Slickgrid. Visit the GitHub repository here, and explore the functionality in action at this demo link. Many thanks for your support!