Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
106
rated 0 times [  109] [ 3]  / answers: 1 / hits: 24768  / 8 Years ago, fri, july 22, 2016, 12:00:00

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.


More From » angular

 Answers
21

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!);
}

[#61279] Wednesday, July 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
freddiejarretk

Total Points: 612
Total Questions: 103
Total Answers: 88

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
;