adrian h.
adrian h.

Reputation: 3026

Angular2 - reset the value of a select after user changes it

I have a <select> which the user can change. Initially it has a value and when the user changes it I must prompt her "are you sure"? and in case the answer is NO then change back the <select>'s selected value to the previous one. The <select> is bound to a collection of objects, not values.

The best I could come up with so far is this:

<select [ngModel]="selectedObj" (ngModelChange)="onSelectedObjChanged($event)">
    <option *ngFor="let obj of availableObjs" [ngValue]="obj">{{whatever}}<option>
</select>
onSelectedObjChanged(obj) {
  if (prompt answer is no) {
     let currentlySelectedObj = this.selectedObj;
     this.selectedObj = null;
     this.changeDetectorRef.detectChanges();
     this.selectedObj = currentlySelectedObj;
     this.changeDetectorRef.detectChanges();
  }
}

This works, but is ugly. Why do I do it:

I'm sure there is a better and easier way to do this, it would be great if you could share some ideas.

Thanks!

Upvotes: 7

Views: 10992

Answers (3)

RVandersteen
RVandersteen

Reputation: 2137

Here's how I did it:

HTML:

<select [(ngModel)]="option"
        #selectModel="ngModel"
        (ngModelChange)="optionChanged($event)">
    <option [ngValue]="null">PlaceHolder</option>
    <option *ngFor="let o of options" [ngValue]="o">...</option>
</select>

Component:

@ViewChild('selectModel') private selectModel: NgModel;

optionChanged($event) {
    //logic
    this.selectModel.reset(null);
}

Upvotes: 11

SoPhat Vathana
SoPhat Vathana

Reputation: 80

try this.selectedObj = obj.target.value; and than perform your condition.

Upvotes: -1

Julie David
Julie David

Reputation: 41

I use $event.target.value instead of $event. I send this.selectedObj = $event.target.value; and if failed change this.selectedObj = previousObject I don't need any change detection.

Upvotes: 0

Related Questions