Angular 4 On select change get attribute data value

前端 未结 4 1492
甜味超标
甜味超标 2021-02-04 19:16

My code in component.html


                        
    
提交评论

  • 2021-02-04 19:45

    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>
    
    0 讨论(0)
  • For Angular material > 7

    Component.ts

    menuChange(event) {
    // _getHostElement : Gets the current Host DOM element
    console.log(event.option._getHostElement().getAttribute('data-somedata'));
    }
    
    0 讨论(0)
  • 2021-02-04 19:53

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

    0 讨论(0)
  • 提交回复
    热议问题