0

How do you cancel a dropdown change event in Angular 2?

HTML:

<select [(ngModel)]="statusId" (change)="onStatusChange($event)">
    <option *ngFor="let status of statuses" [ngValue]="status.id">{{status.text}}</option>
</select>

TS:

onStatusChange(e: Event) {
    var oldStatusId = this.statusId;
    var newStatusId = e.target.value;

    if(this.submitNewValue(newStatusId)){
        console.log('value changed');
    } else {
        console.log('value not changed');
        // How to cancel this and keep the previously selected value in the dropdown?
    }
}
Aximili
  • 26,401
  • 50
  • 141
  • 196
  • 1
    You need this, I think. http://stackoverflow.com/questions/4076770/getting-value-of-select-dropdown-before-change – wannadream May 19 '17 at 04:20
  • @wannadream jQuery fires the event after changing the value, Angular2 does it before changing the value – Aximili May 19 '17 at 04:46
  • 1
    Are you sure? (change) is binding function to onchange event. https://developer.mozilla.org/en-US/docs/Web/Events/change I do not think Angular has a different behavior. – wannadream May 19 '17 at 04:50
  • That's odd... See my code above. `oldStatusId` and `newStatusId` are as I expected – Aximili May 19 '17 at 05:01
  • I see what you mean. The actual data binding update might happen after onchange event. Have you tried e.preventDefault()? – wannadream May 19 '17 at 05:16
  • Looks like two way binding makes the situation complicated. Maybe can you consider to drop two way binding? – wannadream May 19 '17 at 06:00
  • Possible duplicate of [Angular2 Dropdown revert to previously selected option](https://stackoverflow.com/questions/46357952/angular2-dropdown-revert-to-previously-selected-option) – jsalvata Apr 18 '18 at 13:31
  • Did you resolved this? – Cegone Mar 24 '21 at 15:08

1 Answers1

1

You can try this way, notice ngModel is not directly bind :

HTML:

<select (change)="onChange($event, statusId)">
   <option value="" class="dropdown-item">Select Status</option>
   <option *ngFor="let status of statuses" [value]="status.id">{{status.text}}</option>
</select>

TS:

onChange(event, statusId) {
    if (isValid(event.target.value)) {
        statusId = event.target.value;
    }
    else{
        statusId = "";
        event.target.selectedIndex = "0";
    }
}
S. Kundu
  • 11
  • 4