我尝试下面的代码来获取国家的数据属性的值,但没有奏效。
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>
你可以用[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
变量。
您需要选择选项索引来获取所选选项的属性值。
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)。