8

My code in component.html

<select class="form-control input-sm" [(ngModel)]="o.id" formControlName="optionals" (change)="menuChange($event)">
  <option *ngFor="let menu_optional of menu_optionals" value="{{ menu_optional.id }}" [attr.data-somedata]="menu_optional.id">{{ menu_optional.name }}</option>
</select>`

And thi my component.ts

menuChange(event) {
    console.log(event.data);
}

And return is undefined

I want get value in data-somedata..

Rifky Syaripudin
  • 105
  • 2
  • 2
  • 6

4 Answers4

17

As your attr.data-some-data value is the same as value you can simply write:

console.log(event.target.value);

But if you really want to get that data-attribute then use the following code:

const selectEl = event.target;

const val = selectEl.options[selectEl.selectedIndex].getAttribute('data-somedata');
// or
const val = selectEl.options[selectEl.selectedIndex].dataset.somedata;
yurzui
  • 205,937
  • 32
  • 433
  • 399
3

Try like this :

use (ngModelChange) instead of (change)

<select class="form-control input-sm" [(ngModel)]="o.id" formControlName="optionals" (ngModelChange)="menuChange($event)">
  <option *ngFor="let menu_optional of menu_optionals" [value]=" menu_optional.id" [attr.data-somedata]="menu_optional.id">{{ menu_optional.name }}</option>
</select>
Chandru
  • 10,864
  • 6
  • 38
  • 53
0

For the people, who are using MatSelect (Angular material >1) & Reactive form, below one worked for me

HTML

<mat-form-field class="full-width">
    <mat-select placeholder="Field 1" 
      [formControl]="form.controls['field1']" 
      (change)="dropDownChnge($event)">
      <mat-option *ngFor="let fieldOpt of fieldOpts.options" [attr.data-fieldId]="fieldOpts.fieldId" [value]="fieldOpt.id">{{ fieldOpt.name }}</mat-option>
    </mat-select>
</mat-form-field>

Component.js

dropDownChnge(event) {
    let target = event.source.selected._element.nativeElement;
    let selectedData = {
      fieldId: target.getAttribute('data-fieldId'),
      valueId: event.value,
      value: target.innerText.trim()
    };
    console.log(selectedData);
}

If there is best solution or anything wrong in this solution, please let me know, just curious to know :-)

Sivakumar Tadisetti
  • 4,865
  • 7
  • 34
  • 56
  • 1
    +1 for your solution. Just to avoid the console `event.source.selected` `undefined` error, I added an `if/else` statement in the `(selectionChange)` event function, by considering a possible empty selected option: https://stackoverflow.com/a/60386234/2149425 – Riccardo Volpe Feb 25 '20 at 14:49
-2

For Angular material > 7

Component.ts

menuChange(event) {
// _getHostElement : Gets the current Host DOM element
console.log(event.option._getHostElement().getAttribute('data-somedata'));
}
harun
  • 43
  • 9