<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>
I was trying to get selected value from the drop down list and assign it to the onRowClick
function. But myDropDownList
always appears to be undefined
for some reason. I was wondering what might go wrong here.
<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>
I was trying to get selected value from the drop down list and assign it to the onRowClick
function. But myDropDownList
always appears to be undefined
for some reason. I was wondering what might go wrong here.
4 Answers
Reset to default 2Make use of Forms or ngModel for this case . Using Forms
Template
<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>
Component
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
I actually ended up with using ElementRef
as the solution, which in my opinion is probably simpler and more straightforward.
@ViewChild('myDropDownList') myDropDownList: ElementRef;
onRowClick(){
const selectedValue = this.myDropDownList.nativeElement.value;
//...
}
Using forms was just a bit overkill in my case. But thanks for putting it out as another possible alternative.
Change your drop down HTML like the below
<select [(ngModel)]="selectedNumber" (ngModelChange)="onRowClick()" >
<option *ngFor="let n of numbers" value={{n}}>{{n}}</option>
</select>
In TS file you can declare selectedNumber to pass default value or you can use inside onRowClick function to get the selected number
selectedNumber : number = 1;
onRowClick(){
console.log(this.selectedNumber)
}
You can find the working version here
You can pass an event and retrieve 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)
}