Angular4 - Getting "undefined" instead of dropdown selected value

Viewed 1743

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

Use

(ngModelChange)="onCountryChange($event)"

instead of

(change)="onCountryChange()"

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

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

Related