Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current value when change select option - Angular2

Tags:

html

angular

I'm writing an angular2 component and am facing this problem.

Description: I want to push an option value in select selector to its handler when the (change) event is triggered.

Such as the below template:

<select (change)="onItemChange(<!--something to push-->)">
    <option *ngFor="#value of values" value="{{value.key}}">{{value.value}}</option>
</select>

Component Class:

export Class Demo{

  private values = [
     {
        key:"key1",
        value:"value1"
     },
     {
        key:"key2",
        value:"value2"
     }
  ]

  constructor(){}
  onItemChange(anyThing:any){
     console.log(anyThing); //Here I want the changed value
  }
}

How can I get the value(without using jquery) ?

like image 503
Garry Avatar asked Jan 28 '16 07:01

Garry


2 Answers

There is a way to get the value from different options. check this plunker

component.html

<select class="form-control" #t (change)="callType(t.value)">
  <option *ngFor="#type of types" [value]="type">{{type}}</option>
</select>

component.ts

this.types = [ 'type1', 'type2', 'type3' ];

callType(value) {
  console.log(value);
  this.order.type = value;
}
like image 159
Mubashir Avatar answered Oct 09 '22 14:10

Mubashir


In angular 4, this worked for me

template.html

<select (change)="filterChanged($event.target.value)">
  <option *ngFor="let type of filterTypes" [value]="type.value">{{type.display}}
  </option>
</select>

component.ts

export class FilterComponent implements OnInit {

selectedFilter:string;
   public filterTypes = [
     { value: 'percentage', display: 'percentage' },
     { value: 'amount', display: 'amount' }
  ];

   constructor() { 
     this.selectedFilter = 'percentage';
   }

   filterChanged(selectedValue:string){
     console.log('value is ', selectedValue);
   }

  ngOnInit() {
  }
}
like image 38
javed Avatar answered Oct 09 '22 13:10

javed