Ahmad
Ahmad

Reputation: 141

In angular, how to get both the selected text as well as value of the dropdown selected item?

Does any body know, in angular, how to get both the selected text as well as value of the dropdown selected item ?

Code

                     <select
                        [(ngModel)]="model.country"
                        class="
                          form-control form-control-lg form-control-solid
                        "
                        name="country"
                        #cont
                        (change)="onCountrySelected(cont.value)"
                      >
                        <option
                          *ngFor="let country of countriesList"
                          value="{{ country.id }}"
                        >
                          {{ country.name }}
                        </option>
                      </select>

How can I get the text and value on executing the onCountrySelected() function ?

Upvotes: 0

Views: 2221

Answers (1)

David B.
David B.

Reputation: 749

Instead of providing your own parameter to the function you can use the $event keyword to get the actual event data. like so:

(change)="onCountrySelected($event)"

To get the data you want just log the event in your ts and access the properties like so (I don't know the exact type from memory).

onCountrySelected(event: any) {  
  console.log(event); // look in the console to get the properties
  event.target.value // you can access them like that
}

Upvotes: 1

Related Questions