Search code examples
javascriptangulareventsdropdown

Unable to trigger change event when dropdown is autoselected in Angular


In my code below, onColorChanged is not triggered when the selection gets updated programatically. It does trigger when I go to UI and select the color from the dropdown. Not sure what is going on.

          <div class="card border-0">
                <div class="card-body">
                    <label for="color">
                            <b>Color</b>
                    </label>
                    <select class="form-control" ng-init=null id="colorList" aria-describedby="colorList" *ngIf="myColorList$"
                        [(ngModel)]="selectedColor" (change)="onColorChanged(selectedColor)">
                        <option *ngFor="let c of myColorList$ | async" [ngValue]="c">{{c}}</option>
                    </select>
                </div>
            </div>

Solution

  • Pass name attribute to the select tag. Cover select tag in form element.

        <form name="colorForm">
    
            <select class="form-control" id="colorList" name="myColor" [(ngModel)]="selectedColor" (change)="onColorChanged(selectedColor)"> 
    <option *ngFor="let c of myColorList$ | async" [ngValue]="c">{{c}}</option>
     </select>
    </form>