Angular 4 - find selected value in dropdown
Asked Answered
L

4

2

I am using Angular 4 Reactive Forms to create a dropdown

<select id="city" formControlName="city" (change)="onCitySelect($event)" >
    <option *ngFor="let city of cities" [ngValue]="city" >
        {{ city }} 
    </option>
</select> 

When a value is selected in the dropdown, I want to call a method and display the selected value.

Here is my code to do this

onCitySelect(event) {
    console.log(event.target.value);
}

I was expecting it to print the City name as shown in the dropdown. However, it seems it displays the index number as well. For instance,

2: London

Instead of just London which is actually shown in the dropdown.

How can I get the city name without the index?

Lawman answered 29/10, 2017 at 12:29 Comment(1)
The whole point of reactive forms is to have form controls containing the value (and other information) about your inputs. So get the value from the FormControl named "city" in the FormGroup.Favorable
B
7

Use [value] instead of [ngValue] if you have a string or number as option value and don't want to use [(ngModel)]="...".

For object values you always should use [ngValue] though.

Brinkema answered 29/10, 2017 at 14:41 Comment(0)
P
0

Since you are using Angular 4 Reactive Forms, you can do as follows:

let say you have this declaration in your typescript file for your component:

export class myComponent{
    myForm: FormGroup;

    ngOnInit(){
        this.myForm = new FormGroup({
            city: new FormControl('', Validators.required)
        }
    }

    onCitySelect($event:any){
        console.log(this.myForm.controls["city"].value);
    }
}

So you can use: this.myForm.controls["city"].value to access the selected value for city.

Perla answered 29/10, 2017 at 15:3 Comment(0)
D
0

You can subscribe to formControl to fire a function on change of value and hence eliminating this

(change)="onCitySelect($event)" 

You can do this

this.myForm.get('city').valueChanges.subscribe(value=>{
     console.log(value);
})

where 'myForm' is your formGroup which has formControl 'city' so whenever you select value console.log() will happen hence no need to add onChange event

also instead of [ngValue] you can directly give [value] and what ever value you define here will get logged on change

Dine answered 29/10, 2017 at 16:47 Comment(0)
C
0

Simplest solution :

<select (change)="methodToCall($event.target.value)">
                            <option value="" selected>Please select account</option>
                            <option *ngFor='let details of someInformation?.thatIhave'
                                value={{details?.hNum}}>{{details?.hNum}}</option>
                        </select>
Caustic answered 11/4, 2020 at 21:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.