如何在角度6中获取选择属性

问题描述 投票:0回答:2

我尝试下面的代码来获取国家的数据属性的值,但没有奏效。

  fieldId: target.getAttribute('data-country_id'),
   const selectEl = event.target;
   var id = angular.element(event).data('country_id');
  console.log("test"+event.currentTarget.getAttribute("data-id"));
  <select name="state"  [(ngModel)]="model.state"  id="state"  (ngModelChange)="GetCitySelected($event)" >
  <option *ngFor="let state of StateList" value="{{state.id}}" [attr.data-country_id]="state.country_id">{{state.name}}</option>
   </select>
                                            
                                   
angular select attributes angular6 option
2个回答
0
投票

你可以用[value]绑定ngModel来做到这一点。

 <select name="state"  [(ngModel)]="model.state"  id="state"  (ngModelChange)="GetCitySelected($event)" >
      <option *ngFor="let state of StateList" [value]="state" [attr.data-country_id]="state.country_id">{{state.name}}</option>
 </select>

在这里你需要匹配value属性的数据和ngModel变量。


0
投票

您需要选择选项索引来获取所选选项的属性值。

HTML

<select name="state" [(ngModel)]="model.state" (change)="stateChange($event)"  id="state">
  <option *ngFor="let state of StateList" [value]="state.id" [attr.data-country_id]="state.country_id">{{state.name}}</option>
</select>

零件

stateChange(event){
    let selectedIndex:number = event.target["selectedIndex"];
    console.log(event.target.options[selectedIndex].getAttribute("data-country_id"))
}

我为您的解决方案使用(更改)事件而不是(ngModelChange)。

© www.soinside.com 2019 - 2024. All rights reserved.