尝试从 *ngFor
选择选项获取 attr.data-item-code
,我想在单击按钮时获取数据属性值。
<div>
<select>
<option *ngFor="let x in players" [attr.data-item-code]="x.code">{{ x.name }}</option>
</select>
<button (click)="preview()">Preview Player</button>
</div>
我尝试了类似下面的内容,但值为null
<div #dt>
<select>
<option *ngFor="let x in players" [attr.data-item-code]="x.code">{{ x.name }}</option>
</select>
<button (click)="preview(dt.getAttribute('data-item-code'))">Preview Player</button>
</div>
预览功能:--
preview(code){
console.log(code) // returns null
}
当我点击preview()
时,有没有办法获取x.code
?
最佳答案
您可以使用ngModel
,稍后您可以在 preview()
函数中使用 selectedValue
。
<select [(ngModel)]="selectedValue">
<option *ngFor="let x in players" [ngValue]="x.code">{{ x.name }}</option>
</select>
注意:您可以使用[ngValue]="x"
,然后可以从对象selectedValue
访问所需的属性。
关于javascript - Angular2如何获取attr.data-item-code(点击),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44654142/