2

First I should say I went through all answered which posted for similar problem, but none of them worked for me! it's really odd, since the code it seems OK, but still it always give me undefined in change event!

I tried this :

<select name="countries" id="countries" [(ngModel)]="selectedCountry" (change)="onCountryChange()">                            
    <option *ngFor="let x of countries" [ngValue]="x">{{x.CouName}}</option>
</select>

and in my component

 selectedCountry: any[];

 onCountryChange() {  
    console.log(this.selectedCountry);//Give me undefined      
}

Also I tried this :

<select name="countries" id="countries" (change)="onCountryChange($event.target.value)">                            
    <option *ngFor="let x of countries" [ngValue]="x">{{x.CouName}}</option>
</select>

this one also give me undefined

onCountryChange(value) {  
    console.log(value);//Give me undefined      
}

2 Answers 2

3

Use

(ngModelChange)="onCountryChange($event)"

instead of

(change)="onCountryChange()"

(change) is fired before the [(ngModel)]="..." binding was updated.

Sign up to request clarification or add additional context in comments.

5 Comments

I just used ngModelChange as you suggested, but still getting undefined!
Hard to tell without seeing the code. Ideally you could provide a reproduction using stackblitz.com or Plunker. I added the $event parameter.
it's really weird! I reproduced in stackblitz and it's working fine, the same code! but in my project getting undefined! even the $event parameter is undefined! stackblitz.com/edit/angular-z7yniz
Interesting. One observation. selectedCountry should be an object (country) not an array. Otherwise I have no idea.
I changed selectedCountry: any[]; to selectedCountry: Number; and change the ngValue to x.CouId which is a number, now I get the value, Thank you for the answer.
3

This is a known issue with angular.

Select change event occurs before ngModel updates

You should change from (change) to (ngModelChange)

<select name="countries" id="countries" [(ngModel)]="selectedCountry" (ngModelChange)="onCountryChange(selectedObj)">                            
    <option *ngFor="let x of countries" [ngValue]="x">{{x.CouName}}</option>
</select>

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.