Angular | How to Get Dropdown Selected Text using Common Service Method

In Angular, we can easily iterate over the dropdown values using *ngFor directive and get the selected value using its model, but sometimes we have different properties for dropdown value and text which we need to show in options.

In that case, it becomes tricky to fetch the selected dropdown value’s text. Here we will create a service method that can be easily used anywhere in the application to fetch selected value text.

Let’s get started!

For Single Selection:

Add Simple Select / Dropdown

In the template, HTML add following select element with *ngFor to iterate values.

The (change) method selectChange() which we will define in the component class.

The [(ngModel)] will hold selected value in mySelect using binding.

 

Create a method getDropDownText in Service

It’s always a good idea to create reusable methods in service.

Here is the CommonService with getDropDownText the method which takes two inputs, first is id and second is the select object to filter:

 

In the above method, we used the lodash methods _.filter() and _.includes().

The _.filter() method is getting items from the object which matches with our id passed using _.includes() method.

Update Component Class

Now add data object holding the dropdown values, the model variable mySelect and selectedValue which will contain the selected value row.

Get Text of Multiple Dropdown Selections

When multiple properties are set to true then the user can select multiple values. So here we need to show the text value of selection in the list.

So we will make changes in HTML and component class. There is a button also to toggle between single/ multi-selection.

In app.component.html place below code:

Update the app.component.ts file with below code:

 

 

Leave a Reply

avatar
  Subscribe  
Notify of