【问题标题】:Get selected value from the drop down list with Angular使用 Angular 从下拉列表中获取选定的值
【发布时间】:2018-05-04 12:52:49
【问题描述】:
<tr (click)="onRowClick(myDropDownList.value)">
<td>
<select #myDropDownList (click)="$event.stopPropagation()" (change)="onChange($event.target.value)">
<option *ngFor="let n of numbers" [value]="n">{{n}}</option>
</select>
</td>
</tr>
我试图从下拉列表中获取选定的值并将其分配给onRowClick 函数。但出于某种原因,myDropDownList 总是看起来是undefined。我想知道这里可能出了什么问题。
【问题讨论】:
标签:
javascript
html
angular
typescript
select
【解决方案1】:
在这种情况下使用 Forms 或 ngModel 。
使用表单
模板
<form [formGroup]="test">
<div class="col-sm-6 form-group">
<label>Industry</label>
<tr (click)="onRowClick(myDropDownList.value)"> Click
<td>
<select #myDropDownList class="form-control select" formControlName="Industry">
<option [selected] = "true == true" [ngValue] = "0"> Please Select</option>
<option *ngFor="let industry of industries" [ngValue]="industry.id">{{industry.name}} </option>
</select>
</td>
</tr>
</div>
</form>
组件
export class AppComponent implements OnInit {
name = 'Angular 5';
test:FormGroup;
industries = [{id:1,name:"rahul"},{id:2,name:"jazz"}];
ngOnInit(){
this.test = new FormGroup({
Industry:new FormControl('')
});
this.test.get('Industry').valueChanges.
subscribe(data =>
console.log(this.industries.filter(d => {return d.id == data}))
);
}
onRowClick(value){
console.log("called");
alert(value);
}
}
Working Example
【解决方案2】:
我实际上最终使用了ElementRef 作为解决方案,在我看来这可能更简单、更直接。
@ViewChild('myDropDownList') myDropDownList: ElementRef;
onRowClick(){
const selectedValue = this.myDropDownList.nativeElement.value;
//...
}
在我的情况下,使用表单有点过头了。但是感谢您将其作为另一种可能的选择。
【解决方案3】:
如下所示更改您的下拉 HTML
<select [(ngModel)]="selectedNumber" (ngModelChange)="onRowClick()" >
<option *ngFor="let n of numbers" value={{n}}>{{n}}</option>
</select>
在 TS 文件中,您可以声明 selectedNumber 以传递默认值,也可以在 onRowClick 函数中使用来获取选定的数字
selectedNumber : number = 1;
onRowClick(){
console.log(this.selectedNumber)
}
你可以找到working version here
【解决方案4】:
您可以传递一个事件并检索 event.target.value
<select id="accounts">
<option *ngFor="let account of accounts" [value]="account.value" (click)="selectAccount($event)">{{account.name}}</option>
</select>
selectAccount(event){
console.log(event.target.value)
}