deanwilliammills
deanwilliammills

Reputation: 2787

Angular 2 select with (change) event, not updating value in dropdown

When the select dropdown changes, I call a method with the (change) directive to check if the value selected is allowed, if the selected value is not allowed, I select the previous value again (revert the change on the dropdown), but the selected value in die dropdown still shows the new selected value, but the ngModel variable is the previous value e.g. :

I change the select from A to B.

HTML:

<select (change)="doCheck()" [(ngModel)]="test">
    <option [ngValue]="1">A</option>
    <option [ngValue]="2">B</option>
</select>

Component:

test: number = 1;

doCheck(){  
     //Not allowed to change to B, so change back to A
     this.test = 1;
}

The test variable value is 1, but B is still selected in the dropdown.

However when I add a setTimeout on this.test = 1 then the value change back to A, but I don't want to add setTimeout everywhere in my code.

Any help will be appreciated

Upvotes: 4

Views: 10721

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658037

Use ngModelChange instead

<select (ngModelChange)="doCheck()" [(ngModel)]="test">

to ensure doCheck() is called after ngModel updated test

Angular doesn't guarantee event bindings to be processed in any specific order. But ngModelChange is emitted by NgModel after it updated the model.

If you modify the value back that ngModel did update you probably need

constructor(private cdRef:ChangeDetectorRef) {}

doCheck(){  
     //Not allowed to change to B, so change back to A
     this.test = 1;
     this.cdRef.detectChanges();
}

otherwise ngModel might keep the old value.

Upvotes: 4

Related Questions