如何从选定的选项值中获取数据属性?
这些似乎很容易做,但是我不知道怎么做!
尝试使用$event
,并使用this.form.get('controlName')
获得控件
<select (change)='handleChange($event)' [formControlName]="places">
<option *ngFor="let place of places"
[attr.data-one]='place.custom-attr-one'
attr.data-two='{{place.another-info}}'
data-three='{{place.guess-what}}'
[value]="opt.key">{{opt.value}}</option>
</select>
我最终得到了这些,但感觉很脏。
handleChange(event: any) {
console.log('change select', event.target[event.target.selectedIndex].dataset);
}
我知道数据属性是来自选项的,而不是来自select的,但是select不能在没有Option的情况下工作,因此在我看来,formcontrol this.form.get('controlName')
上具有这些信息是很自然的。
有一种惯用的方式将信息附加到单个选项(虽然不在值上)并在选择项上发生更改事件?
您可以试试吗?>
const selectEl=event.target;
const val = selectEl.options[selectEl.selectedIndex].getAttribute('data-one');
// or
const val = selectEl.options[selectEl.selectedIndex].dataset.one;