Home > Mobile >  Angular 13 get Value And Label from Select Option
Angular 13 get Value And Label from Select Option

Time:06-02

i want to get the value and label of my select option and mapp the to my reactive Form. this is my html:

  <select  (change)="onChange($event.target)">
    <option value=""></option>
    <option value="C1">Country 1</option>
    <option value="C2">Country 2</option>
    <option value="C3">Country 3</option>
  </select>

and this is my ts code :

  onChange(event: any) {
    // here i want to get the value and label of my selected item (C2 , Country 2 for example)
    console.log(event.value); // this print only the value C1,2,3
  }

CodePudding user response:

Updated Answer

HTML:

 <select (change)="onChange($event)" formControlName="country"></select>

TS:

  onChange($event: any) {
    let text = $event.target.options[$event.target.options.selectedIndex].text;

    this.yourForm.patchValue({ labelText: text });

    console.log(text);
  }

The (change) should get the text that represents the option, and the formControlName should retrieve the value from the option.

patchValue will change the form value for the value that you want, you just need to type the name of the formControl: labelText and after the : the desired value!

About the value from the option, if you have a formControlName on the select, it will automatically change the formControl value!

CodePudding user response:

In your component.ts declare a variable / collection of options = [{value:'some value', label:'some label'}, {value:'some value', label:'some label'}, {value:'some value', label:'some label'}]; public anothervariableToHoldTheSelectedOption = null;

in component.html file

<select [(ngModel)]="anothervariableToHoldTheSelectedOption"> <option *ngFor="let option of options" value="option">{{option.label}}

In this way you will have a whole object in the holdingObject. you can do anything with it.

  • Related