Sam
Sam

Reputation: 14586

Angular PreventDefault on change event is not working

For a select element I'm trying to prevent the value from changing based on some conditions:

<select [ngModel]="selectedPriority" (change)="onPriorityChanged($event)">
  <option *ngFor="let priority of priorities" [ngValue]="priority">{{priority.label}}</option>
</select> 

onPriorityChanged(event) {
  event.preventDefault();
  return false;
}

This is not working. The model is not updated because I use 1-way binding but the selected item in the select changes, even though I use preventDefault.

What is the correct way to achieve this ?

Upvotes: 5

Views: 8895

Answers (1)

Gourav Pokharkar
Gourav Pokharkar

Reputation: 1638

'change' event is not cancellable: Refer(https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event and https://stackoverflow.com/a/24252333/6848923)

You can reset value in ngModel on change event if you want to prevent the selection for a particular condition.

Upvotes: 5

Related Questions