Search code examples
javascriptangulartypescriptselectdropdown

Angular2 Dropdown revert to previously selected option


I have this simple HTML select to implement dropdown in Angular2 (TS) as shown below

<select id="pageSize" (change)="onPageSizeChanged($event, pagination.pageSize)">
  <option value="10">10</option>
  <option value="20">20</option>
  <option value="50">50</option>
</select>

The previously selected value is kept in pagination.pageSize variable. And on change of this I wanted to open a dialog box and wait for users response. If user, clicks cancel I want to revert the selection to the previously selected options.

onPageSizeChanged(event, oldValue) {
  const response = window.confirm("Are you sure you want change the page size? Your edits will be lost?");
  if (response) {
    //... some code ...
  } else {
    //... here I want to revert the selection to previously selected option
  }
}

Tried lot of different things but of no luck.

Please help, I am loosing my mind over this simple thing. I must be doing something stupid.


Tries #1 - Didn't work (Plunk - https://embed.plnkr.co/ILi12O/)

<select id="pageSize" [ngModel]="pageSize" (ngModelChange)="onPageSizeChanged($event, pagination.pageSize)"> 
  <option value="10">10</option> 
  <option value="20">20</option> 
  <option value="50">50</option> 
</select> 

onPageSizeChanged(event, oldValue) { 
  const response = window.confirm("Are you sure you want change the page size? Your edits will be lost?"); 
  if (response) { //go ahead so something } 
  else { this.pageSize = oldValue; }  
} 

Solution

  • Add ngModelChange to track the model changes. Keep the change if the dialog confirms for the next change, otherwise set back the value. Local template variable (#select) make a little easier to track. I made changes based on your plunker:

    HTML:

     <select #select id="pageSize" [ngModel]="pageSize" (ngModelChange)="select.value = onPageSizeChanged($event)"> 
    

    TypeScript:

       onPageSizeChanged(event) { 
       const response = window.confirm("Are you sure you want change the page size? Your edits will be lost?"); 
        console.log(this.pagination.pageSize)
        if (response) { 
          this.pageSize = event;
          this.pagination.pageSize = event;
        }
        else{
          this.pageSize = this.pagination.pageSize;
        }
        return this.pagination.pageSize;
      } 
    

    demo