0
votes

I am fairly new to Angular2, and am working on a small POC, where I want to show a list of options in a dropdown to the user, the user will then select one of the options, and then I want to update a model with the ID of the selection option.

Everything works fine till the time I just display the dropdown and data in it, using the following code:

  <select>
    <option *ngFor="let th of townHalls" [value]="th.id">{{th.name}}</option>
  </select>

However, considering that th.id is a number, when I changed the code to use ngValue instead of value, the code stops working.

  <select>
    <option *ngFor="let th of townHalls" [ngValue]="th.id">{{th.name}}</option>
  </select>  

In addition to this, if I add ngModel to select, then again the code stops working. Below is the code I am using:

<select [(ngModel)]="townHall">

I am not able to understand what I am doing wrong here. Here is the link to the plunker: https://plnkr.co/edit/8FhZpXzgwLU0EJMZVNsm?p=preview

TIA.

1
Did you initialize townHall?jeanl
I've defined it in app.ts: townHall: number; Do I need to initialize it as well, will it by default not take undefined value and be updated when I select any option from Drop down?Logan
Did you forget to import FormsModule? plnkr.co/edit/j8boYur7NYPhjrcKLyX3?p=previewyurzui
@yurzui Yeah, seems to be the case. Thanks for pointing it out. :)Logan

1 Answers

4
votes

You need to import FormsModule in your src/app.ts

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {TOWNHALLS} from '../townHalls.ts'
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@Component({
  selector: 'my-app',
  templateUrl: 'app.html',
})
export class App {
  name:string;
  townHalls= TOWNHALLS;
  townHall: number;

  constructor() {

  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule  ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}