4

I want to call the function when some value of Dropdownlist is selected and that function will use the selected value's id. How could i bind the selected value's id to model? I can load data to the dropdownlist.

<select>
  <option *ngFor="let category of categorylist" >
             {{ category.Description }}</option>
                     </select>
Amir
  • 1,855
  • 3
  • 24
  • 40

2 Answers2

3

2 way binding in angular2 can be customized and we can call upon our own function. Just bind the id to the ngValue and have that value go on the DropdownChange event.

HTML:

<select [ngModel]="selectedValue" (ngModelChange)="onDropdownChange($event)" class="form-control">
        <option *ngFor="let category of categorylist" [ngValue]="category.id">{{category.Description}}</option>
     </select>  

COMPONENT:

onDropdownChange(e){
  console.log(e)//you will get the id  
  this.selectedValue =e //if you want to bind it to your model
}
Sunil Lama
  • 4,531
  • 1
  • 18
  • 46
0
<select [(ngModel)]="selectedCategory">
  <option *ngFor="let category of categorylist" [ngValue]="category" >
             {{ category.Description }}</option>
                     </select>

You read and set the selected option by reading and assigning to selectedCategory.

If the value is an object (not a primitive value) then the instance assigned to selectedCategory must be the same as in [ngValue]. Just another instance with the same properties and values is not enough.

See also Binding select element to object in Angular 2

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I want to bind selected value's id – Amir Dec 04 '16 at 16:39
  • That's the easier version. Just use `[value]="category.id"` or `[ngValue]="category.id"`. I just explained the more trickier one and assumed you'll be able to figure out the easier one by yourself. – Günter Zöchbauer Dec 04 '16 at 16:40
  • I am getting error Can't bind to 'ngModel' since it isn't a known property of 'select'. should i import any other component ? – Amir Dec 04 '16 at 16:51
  • You need to add `FormsModule` to in your `@NgModule({imports: [BrowserModule, FormsModule], ...})` (for `AppModule`) or `@NgModule({imports: [CommonModule, FormsModule], ...})` for other modules. – Günter Zöchbauer Dec 04 '16 at 16:53