2

Is it possible to two-way databind to a 'select' dropdown like below?

<select [(ngModel)]="selectedSport">
  <option *ngFor="let s of sports" [value]="s">{{s.Name}}</option>
</select>

I'm unable to get it to work. I've also tried binding just the ID but can't get that working either. See Plnkr here

I used the 'quickstart' live plnkr example from the angular site as a base.

The error I get is:

Can't bind to 'ngModel' since it isn't a known property of 'select'.

Update

Thanks Günter. I've realised I need to update from RC4 to RC5. I have tried the same thing using the angular "form" plnkr example (so the forms module is loaded). I'm still unable to get it to work with RC5. Is it possible to bind a select to an "object" or does it have to be a value type like a number? Thank you.

Second plnkr

Solution

See both Günter's answer and comment. I upgraded from RC4 to RC5, imported the FormsModule, and had to use [ngValue] instead of [value] on the 'option' element.

<select [(ngModel)]="selectedSport">
  <option *ngFor="let s of sports" [ngValue]="s">{{s.Name}}</option>
</select>
user2444499
  • 679
  • 6
  • 13

1 Answers1

1

You need to load the forms module

import { FormsModule } from '@angular/forms';

@NgModule({
imports: [ FormsModule, ... ],
Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
  • 1
    I also got the impression `[value]` also supports objects in RC.5 but this doesn't seem to be the case. For non-string values you still need to use `[ngValue]="..."` http://plnkr.co/edit/CG7btYCdRZQ2OgAyChn5?p=preview – Günter Zöchbauer Aug 16 '16 at 07:26
  • 1
    Fantastic. Thanks very much Günter. Now I just have to upgrade from RC4 to 5 :) – user2444499 Aug 16 '16 at 07:56