答案 0 :(得分:1)
似乎我找到了更优雅的解决方案,它基于this answer。这个想法是操纵<select>
的{{1}}。因此,这是模板:
selectedIndex
和组件:
<form class="form-inline mt-3">
<div class="container-fluid">
<div class="row">
<div class="form-group col-12">
<label for="states" class="mr-3">State</label>
<select #s id="states" class="form-control" name="states" [ngModel]="selectedState"
(ngModelChange)="onStateChange(selectedState, $event, s)">
<option [ngValue]="null">All</option>
<option *ngFor="let state of states" [ngValue]="state">{{state.name}}</option>
</select>
</div>
</div>
</div>
</form>
onStateChange(previousState: State, state: State, statesEl: HTMLSelectElement): void {
// If we're changing state from "All" to any, it's OK
if (previousState === null) {
this.selectedState = state;
return;
}
// Otherwise we want the user to confirm that change
if (confirm('Are you sure you want to select another state?')) {
this.selectedState = state;
} else {
statesEl.selectedIndex = this.states.indexOf(previousState) + 1;
}
}
是必要的,因为+1
在null
的第一个this.states
状态中,而在<select>
之外。