I have a <select> which the user can change. Initially it has a value and when the user changes it I must prompt her "are you sure"? and in case the answer is NO then change back the <select>'s selected value to the previous one. The <select> is bound to a collection of objects, not values.
The best I could come up with so far is this:
- in the html
<select [ngModel]="selectedObj" (ngModelChange)="onSelectedObjChanged($event)">
<option *ngFor="let obj of availableObjs" [ngValue]="obj">{{whatever}}<option>
</select>
- in the code
onSelectedObjChanged(obj) {
if (prompt answer is no) {
let currentlySelectedObj = this.selectedObj;
this.selectedObj = null;
this.changeDetectorRef.detectChanges();
this.selectedObj = currentlySelectedObj;
this.changeDetectorRef.detectChanges();
}
}
This works, but is ugly. Why do I do it:
- there seems to be no way to cancel the selection changed event in the DOM
- when
onSelectedObjChangedis called and the answer is "no", I need to somehow let angular know it has to refresh the binding target, i.e. the<select>... - ...however I can't simply set
this.selectedObj = this.selectedObjas the value doesn't change and there no change detected by angular; that's why I set it tonulland back... - ...however even that is not enough, I need to invoke
changeDetectorRef.detectChanges()to notify angular of it
I'm sure there is a better and easier way to do this, it would be great if you could share some ideas.
Thanks!