Aximili
Aximili

Reputation: 29484

Angular2: How to cancel a dropdown change event?

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?
    }
}

Upvotes: 0

Views: 4399

Answers (1)

S. Kundu
S. Kundu

Reputation: 21

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";
    }
}

Upvotes: 2

Related Questions