[英]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.