0

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.

4
  • Did you initialize townHall? Commented Mar 8, 2018 at 7:20
  • 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? Commented Mar 8, 2018 at 7:22
  • Did you forget to import FormsModule? plnkr.co/edit/j8boYur7NYPhjrcKLyX3?p=preview Commented Mar 8, 2018 at 7:22
  • @yurzui Yeah, seems to be the case. Thanks for pointing it out. :) Commented Mar 8, 2018 at 7:25

1 Answer 1

4

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 {}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.