Reputation: 587
This may have been asked, but i've tried googling for sometime without having getting any solution.
I have the following select field in Angular2, how do i access the stored value in the data attribute of attr.data-thisdata
?
<select #dial">
<option *ngFor="let something of somethings"
[value]="something.value"
[attr.data-thisdata]="something.data"
>{{something.text}}</option>
</select>
I have tried the following but not getting any values:
<select (change)="readData($event.target.dataset)>...<select>
<select (change)="readData($event.target.dataset.thisdata)>...<select>
My readData is simply:
readData(data:any){
console.log(data)
}
EDIT 1: added plunker for ease of reference
EDIT 2: included plunker from Günter's answer
Upvotes: 2
Views: 4121
Reputation: 51
To answer the original question of how to access a data attribute of an option element through a select element's event, use:
event.target[event.target.selectedIndex].dataset.thisdata
The reason event.target.dataset.thisdata
does not work is the data attribute actually belongs to the option, but the event here is coming from the select element. We can access the selected option by using the select's selectedIndex property.
Upvotes: 4
Reputation: 658263
With [ngValue]
instead of value you can assign an object instead of only a string.
<select #dial" ngModel (ngModelChange)="$event.data">
<option *ngFor="let something of somethings"
[ngValue]="something"
[attr.data-thisdata]="something.data"
>{{something.text}}</option>
</select>
Upvotes: 1