typescript Angular 4 On 选择更改获取属性数据值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46860096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 4 On select change get attribute data value
提问by Rifky Syaripudin
My code in component.html
我在 component.html 中的代码
<select class="form-control input-sm" [(ngModel)]="o.id" formControlName="optionals" (change)="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>`
And thi my component.ts
这就是我的 component.ts
menuChange(event) {
console.log(event.data);
}
And return is undefined
而回报是 undefined
I want get value in data-somedata..
我想在 data-somedata 中获得价值..
回答by yurzui
As your attr.data-some-data
value is the same as value
you can simply write:
由于您的attr.data-some-data
价值与value
您可以简单地编写相同:
console.log(event.target.value);
But if you really want to get that data-attribute then use the following code:
但是,如果您真的想获得该数据属性,请使用以下代码:
const selectEl = event.target;
const val = selectEl.options[selectEl.selectedIndex].getAttribute('data-somedata');
// or
const val = selectEl.options[selectEl.selectedIndex].dataset.somedata;
回答by Chandru
Try like this :
像这样尝试:
use (ngModelChange) instead of (change)
使用 (ngModelChange) 而不是 (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>
回答by Sivakumar Tadisetti
For the people, who are using MatSelect (Angular material >1) & Reactive form, below one worked for me
对于使用 MatSelect (Angular material >1) & Reactive form 的人来说,下面的一个对我有用
HTML
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
组件.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 :-)
如果此解决方案有最佳解决方案或任何错误,请告诉我,只是想知道:-)
回答by harun
For Angular material > 7
对于角材料 > 7
Component.ts
组件.ts
menuChange(event) {
// _getHostElement : Gets the current Host DOM element
console.log(event.option._getHostElement().getAttribute('data-somedata'));
}