javascript - Angular2 - reset the value of a select after user changes it -


i have <select> user can change. has value , when user changes must prompt "are sure"? , in case answer no change <select>'s selected value previous one. <select> bound collection of objects, not values.

the best come far this:

  • in html
<select [ngmodel]="selectedobj" (ngmodelchange)="onselectedobjchanged($event)">     <option *ngfor="let obj of availableobjs" [ngvalue]="obj">{{whatever}}<option> </select> 
  • in code
onselectedobjchanged(obj) {   if (prompt answer no) {      let currentlyselectedobj = this.selectedobj;      this.selectedobj = null;      this.changedetectorref.detectchanges();      this.selectedobj = currentlyselectedobj;      this.changedetectorref.detectchanges();   } } 

this works, ugly. why do it:

  • there seems no way cancel selection changed event in dom
  • when onselectedobjchanged called , answer "no", need somehow let angular know has refresh binding target, i.e. <select>...
  • ...however can't set this.selectedobj = this.selectedobj value doesn't change , there no change detected angular; that's why set null , back...
  • ...however not enough, need invoke changedetectorref.detectchanges() notify angular of it

i'm sure there better , easier way this, great if share ideas.

thanks!

here's how did it:

html:

<select [(ngmodel)]="option"         #selectmodel="ngmodel"         (ngmodelchange)="optionchanged($event)">     <option [ngvalue]="null">placeholder</option>     <option *ngfor="let o of options" [ngvalue]="o">...</option> </select> 

component:

@viewchild('selectmodel') private selectmodel: ngmodel;  optionchanged($event) {     //logic     this.selectmodel.reset(null); } 

Comments