2

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:

  1. <select (change)="readData($event.target.dataset)>...<select>
  2. <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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Plunker example

5 Comments

but something is only defined in the <option *ngFor="let something of somethings">?
it's not working, i added readData to your (ngModelChange)="$event.data i get undefined..
Can't imagine. Can you reproduce in a Plunker?
yep, added the plunker
ok, i got it now, with ngValue and having assigned an object to it, there wont be a need to use data attribute right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.