Get selected value from the drop down list with Angular

17,275

Solution 1

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.

Solution 2

Make 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

Share:
17,275

Related videos on Youtube

woodykiddy
Author by

woodykiddy

Updated on June 04, 2022

Comments

  • woodykiddy
    woodykiddy almost 2 years
    <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.