[英]Get selected value from the drop down list with Angular
<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
。 我想知道这里可能出了什么问题。
在这种情况下使用 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);
}
}
我实际上最终使用ElementRef
作为解决方案,在我看来这可能更简单、更直接。
@ViewChild('myDropDownList') myDropDownList: ElementRef;
onRowClick(){
const selectedValue = this.myDropDownList.nativeElement.value;
//...
}
就我而言,使用表单有点矫枉过正。 但是感谢您将其作为另一种可能的选择。
更改您的下拉 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)
}
您可以传递事件并检索 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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.