Can the selection of an HTML <select>
be changed within its own change event handler?
The code I have functions perfectly. It removes the selected item from the drop-down, adds it to another array, and resets the selection of the <select>
to the null
element, displaying as -- Please select filter --
on the page.
<select class="form-select form-select-sm" [(ngModel)]="selectedFilter">
<option [ngValue]="null" [disabled]="true">-- Please select filter --</option>
<option *ngFor="let flt of availableFilters; let idx = index" [ngValue]="flt">{{ flt.caption }}</option>
</select>
<button class="btn btn-sm btn-primary" (click)="addFilter()" [disabled]="!selectedFilter"><i class="fa fa-plus"></i></button>
selectedFilter: AvailableFilter | null;
// [snip]
addFilter(): void {
if (this.selectedFilter) {
this.addFilterInternal(this.selectedFilter);
}
}
private addFilterInternal(flt: AvailableFilter): void {
// Add filter to active filters
this.activeFilters.push(flt);
// Remove filter from available filters
let idx = this.availableFilters.indexOf(flt);
this.availableFilters.splice(idx, 1);
// Reset filter selection drop-down
this.selectedFilter = null;
}
// [snap]
Users requested that the functionality triggered by the button should occur upon selection. Therefore, I added a change
listener to the <select>
that invokes the same component function.
<select class="form-select form-select-sm" [(ngModel)]="selectedFilter" (change)="addFilter()">
<option [ngValue]="null" [disabled]="true">-- Please select filter --</option>
<option *ngFor="let flt of availableFilters; let idx = index" [ngValue]="flt">{{ flt.caption }}</option>
</select>
<button class="btn btn-sm btn-primary" (click)="addFilter()" [disabled]="!selectedFilter"><i class="fa fa-plus"></i></button>
However, this approach does not produce the expected results. The selected element is still removed from the drop-down and added to the other array, but the <select>
does not reset to the null
element. This might be due to being inside the change listener scope.
I attempted to encapsulate the this.selectedFilter = null
code within a subscription to a Subject
, so it executes asynchronously once the function completes (the function calls next()
and complete()
on the Subject after moving the item between arrays). Unfortunately, this did not resolve the issue, as the behavior of the drop-down remains unchanged.