Reputation: 21671
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
Upvotes: 2
Views: 3259
Reputation: 28738
Or this by adding a template variable and getting the value and the id of your element:
<select #mySelect id="regionSelection" [(ngModel)]="regionId"
(change)="onChange(mySelect.value, mySelect.id)"
class = "form-control">
<option *ngFor="let r of regionsForDDL"
value="{{ r.key }}">{{ r.value }}</option>
</select>
Upvotes: 1
Reputation: 55453
other way is to use a #template
variable as shown below,
<select id="regionSelection"
[(ngModel)]="regionId" #target // added #target
(change)="onChange(regionId,target.id)" // changed onChange(regionId,target.id)
class = "form-control">
<option *ngFor="let r of regionsForDDL"
value="{{ r.key }}">{{ r.value }}</option>
</select>
onChange(value, id) {
console.log(value);
console.log(id);
}
Upvotes: 1
Reputation: 214335
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
Upvotes: 4
Reputation: 105563
Just pass it like this:
(change)="onChange($event.target.id, $event.target.value)"
onChange(id: string, selectedValue: string) {
}
Upvotes: 5