1

I want to get the selected text in Angular when I select an item in Dropdownlist.

Please Note that I want to get the text without any onchange event in Dropdownlist. I use query selector to get the value of Dropdownlist and event is button and button inside form tag. Here is my code

const ddldepartment = target.querySelector('#ddldepartment').value;
const ddldesignation = target.querySelector('#ddldesignation').value;

Here I get the value like 1 and 2 not getting the text. and I am using

<form (submit)="PostEmployee($event)">

and

PostEmployee(event) {
    const ddldepartment = target.querySelector('#ddldepartment').value;
    const ddldesignation = target.querySelector('#ddldesignation').value;
}

Here is my HTML Code for the dropdownlist:

<select id="ddldepartment" [(ngModel)]="ddldepartment" name='ddlbankcode' style="width: 70%">
    <option value=0>Choose...</option>
    <option class='option' *ngFor="let dept of department" [value]="dept.dept_code">
      {{dept.dept_name}}
    </option>
</select>

I got value in console. I want to get text. How can I find it?

fiza khan
  • 1,280
  • 13
  • 24
Rifat Murtuza
  • 119
  • 3
  • 12

1 Answers1

1

You're already using [(ngModel)]="ddldepartment". So you'll already have the selected value in the ddldepartment property.

All you need to do is use [ngValue]="dept.dept_name"

Like this:

<form (submit)="postEmployee()">
  ...
  <select 
    id="ddldepartment" 
    [(ngModel)]="ddldepartment" 
    name='ddlbankcode'>
    <option value='null'>Choose...</option>
    <option 
      class='option' 
      *ngFor="let dept of department" 
      [ngValue]="dept.dept_name">
      {{ dept.dept_name }}
    </option>
  </select>
  ...
  <button>Submit</button>
</form>

So in your Class:

postEmployee() {
  // This will give you the selected department name text
  console.log(this.ddldepartment);
}

Here's a Sample StackBlitz for your ref.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110