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.

<h4>Select Value</h4>

<select name="my-select" [(ngModel)]="mySelect" (change)="selectChange()">
    <option [value]="item.id" *ngFor="let item of data">
        {{item.name}}
    </option>
</select>


<h4>Selected Values</h4>

<div>
    Selected: {{selectedValue}}
</div>

 

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:

// services/common.service.ts
import { Injectable } from '@angular/core';
import * as _ from 'lodash';

@Injectable({
  providedIn: 'root'
})
export class CommonService {
  constructor() { }

  getDropDownText(id, object){
    const selObj = _.filter(object, function (o) {
        return (_.includes(id,o.id));
    });
    return selObj;
  }

}

 

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.

// app.component.ts
import { Component, OnInit } from '@angular/core';
import { CommonService } from 'src/app/services/common.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{


  mySelect = '2';
  selectedValue: any;

  data = [
    {
      id: 1,
      name: 'Dakota Gaylord PhD',
      address: '14554 Smith Mews'
    },
    {
      id: 2,
      name: 'Maria Legros',
      address: '002 Pagac Drives'
    },
    {
      id: 3,
      name: 'Brandyn Fritsch',
      address: '8542 Lowe Mountain'
    },
    {
      id: 4,
      name: 'Glenna Ward V',
      address: '1260 Oda Summit'
    },
    {
      id: 5,
      name: 'Jamie Veum',
      address: '5017 Lowe Route'
    }
  ];

  constructor(
    private commonService: CommonService
  ) { }

  ngOnInit() {
  }

  selectChange() {
      this.selectedValue = this.commonService.getDropDownText(this.mySelect, this.data)[0].name;
  }
}

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:

<div>
    <button class="btn btn-primary" (click)="multiple = !multiple; selectedValue = undefined">
        Multiple 
        <span *ngIf="multiple">ON</span>
        <span *ngIf="!multiple">OFF</span>
    </button>
</div>

<h4>Select Value</h4>

<select name="my-select" [(ngModel)]="mySelect" (change)="selectChange()" [multiple]="multiple">
    <option [value]="item.id" *ngFor="let item of data">
        {{item.name}}
    </option>
</select>


<h4>Selected Values</h4>

<ng-container *ngIf="multiple; else elseTemplate">
    <div>
        Selected:
        <ul>
            <li *ngFor="let si of selectedValue">{{si.name}}</li>
        </ul>
    </div>
</ng-container>
<ng-template #elseTemplate>
    <div>
        Selected: {{selectedValue}}
    </div>
</ng-template>

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

// app.component.ts
import { Component, OnInit } from '@angular/core';
import { CommonService } from 'src/app/services/common.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{


  mySelect = [];
  selectedValue: any;
  multiple = true;

  data = [
    {
      id: 1,
      name: 'Dakota Gaylord PhD',
      address: '14554 Smith Mews'
    },
    {
      id: 2,
      name: 'Maria Legros',
      address: '002 Pagac Drives'
    },
    {
      id: 3,
      name: 'Brandyn Fritsch',
      address: '8542 Lowe Mountain'
    },
    {
      id: 4,
      name: 'Glenna Ward V',
      address: '1260 Oda Summit'
    },
    {
      id: 5,
      name: 'Jamie Veum',
      address: '5017 Lowe Route'
    }
  ];

  constructor(
    private commonService: CommonService
  ) { }

  ngOnInit() {
  }

  selectChange() {
    if (this.multiple) {
      this.selectedValue = this.commonService.getDropDownText(this.mySelect, this.data);
    } else {
      this.selectedValue = this.commonService.getDropDownText(this.mySelect, this.data)[0].name;
    }
  }

}

 

 

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments