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..
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;
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>
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 :-)
For Angular material > 7
Component.ts
menuChange(event) {
// _getHostElement : Gets the current Host DOM element
console.log(event.option._getHostElement().getAttribute('data-somedata'));
}