Angular2:如何取消下拉更改事件?

时间:2017-05-19 04:02:12

标签: angular

如何取消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?
    }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试这种方式,请注意ngModel没有直接绑定:

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";
    }
}
相关问题