lowcrawler
lowcrawler

Reputation: 7549

How to get the value in a select change event in angular2

I want to navigate useing a dynamically generated select drop down. It doesn't appear I can do that directly, so I'd simply like to make a function call when the select changes.

To do that, I have this:

---In the template---

<select (change)="navSelected($event)">
    <option *ngFor="let button of navButtons;"
    value="button.route" >{{button.label}}</option>
</select>

suffice it to say that 'navButtons' is an array of objects that have a 'label' field.

---In the class---

navSelected(navName) {
    console.log(navName + " Clicked!");
}

This actually works fine.

I got to this point from the great help of Mark Rajcok and his answer in this older question: How can I get new selection in "select" in Angular 2?

That said, I'd like to be able to pass the selected value in the navSelected() function call. I'm unsure how to do that.

I have tried adding [ngValue]="button" on a wild guess from other searches to the option tag and then referencing the button variable in the (change) event handler (so: (change)="navSelected(button.label)" and other combos, to no avail. I've seen a lot of references to ngModel but they seem old and I'm not entirely sure they apply anymore (and I couldn't get them to work anyway in RC4).

I could probably pull some jquery or whatever out to find the select and get it's value, but that seems very rinky-dink compared to simply being able to call the function correctly.

Upvotes: 9

Views: 25359

Answers (3)

Keegs
Keegs

Reputation: 490

Instead of $event. Try using the below typecast function.

$any($event.target).value

Which will stop the type checking in the template.

Upvotes: 0

eltonkamami
eltonkamami

Reputation: 5190

The value you are looking for is on the $event.target and you can get it with $event.target.value, see my example below.

navSelected($event) {
    console.log($event.target.value + " Clicked!");
}

If you are looking to get the selected text of the option you can do this

navSelected($event) {
    let selectElement = $event.target;
    var optionIndex = selectElement.selectedIndex;
    var optionText = selectElement.options[optionIndex];
    console.log(optionText + " Clicked!");
}

Upvotes: 15

Stef Geysels
Stef Geysels

Reputation: 1047

As a shortcut for @eltonkamami 's answer, you can pass your object like this:

<select (change)="navSelected(navButtons[$event.target.selectedIndex])">
    <option *ngFor="let button of navButtons;">{{button.label}}</option>
</select>

And capture it like this:

navSelected(button: [type of navButtons]){
    console.log(button);
}

Upvotes: 1

Related Questions