Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: When onChange is triggered, How to retrieve both the selected value and the id of the select element?

Here's the code in the template:

<select id="regionSelection" [(ngModel)]="regionId"
        (change)="onChange($event.target.value)"
        class = "form-control">
              <option *ngFor="let r of regionsForDDL"
               value="{{ r.key }}">{{ r.value }}</option>
</select>

and the code in the component

onChange(selectedValue: string) {

}

$event.target.value only sends the selected value. How do I get both the selected value and the id of the element (here regionSelection)?

Thanks for helping

like image 970
Richard77 Avatar asked Jan 19 '26 18:01

Richard77


2 Answers

Just pass it like this:

(change)="onChange($event.target.id, $event.target.value)"

onChange(id: string, selectedValue: string) {

}
like image 143
Max Koretskyi Avatar answered Jan 22 '26 19:01

Max Koretskyi


html

(change)="onChange($event.target)"

ts

onChange({ id, value }) {
   console.log(id, value);
}

or

onChange({ id, value: selectedValue }) {
  console.log(id, selectedValue);
}

https://stackblitz.com/edit/angular-7ysmjr?file=app%2Fapp.component.ts

See more details about how destructuring assignment syntax works

  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Unpacking_fields_from_objects_passed_as_function_parameter
like image 20
yurzui Avatar answered Jan 22 '26 20:01

yurzui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!