Learn how to determine which dropdown menu the user selected in your Angular template, and get its value.
Dropdown elements provide a way to give your visitors choices. Technically, a dropdown element is actually a select element and each menu item in the dropdown is an option element. In a pure HTML-based form, there is virtually no work to do; the browser takes care of all the heavy-lifting. But with Angular, you need to do a little bit of the work. The key is to examine the event object. It contains information about the user’s action.
The reason that we care about the event object is that the select element contains one or more children, and we are going to attach a handler to the (change) event of the select element. But, hold on… even though a change event fired on the select element, we’re concerned with more than just the fact that there was a change; we want to know which one of the option elements was selected. So to do this, we need to take a look at the event object that is passed to the handler assigned to the change event of the select element. And when we look at that event object, we want to pay particular attention to the event target, and get its value. For instance: “event.target.value”, in Example #1.
Example # 1
In Example # 3 we have the contents or our component. There is a selectedDay property, which will be used to display the value of the selected dropdown menu item. There is also a selectChangeHandler method. This method takes an event object as its sole argument. When executed, this.selectedDay is set to the value of the event.target.value property.
So here, you’ll see our event handler because it’s generally considered best practice to define methods in your component, and then assign those methods to the event attributes of the HTML elements in your template. In Example # 2, however, you’ll see that we assign the selectChangeHandler method to the (click) attribute of our select element in the template.
Example # 2
In Example # 2, we have our Angular template. There is a select element, which has five option elements inside of it. Each of these option elements translates to a dropdown menu choice.
The select element has a change attribute. We assign that change attribute to the radioChangeHandler method, passing it the $event object. In ourselectChangeHandler method (see Example # 1), we take a look at the event object. That is, we want to know about its event.target.value property. We set the value of that property to the selectedDay property of our component (in the radioChangeHandler method, we refer to it as this.selectedDay). By setting the selectedDay property of our component, the UI is updated with whatever value is assigned to that property.
Video Example Code
If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-angular-option-get-value