Angular 4 On select change get attribute data valu

2020-05-24 09:24发布

问题:

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..

回答1:

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;


回答2:

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>


回答3:

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 :-)



回答4:

For Angular material > 7

Component.ts

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