Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding ngModel to a model for a select control [duplicate]

Tags:

angular

In Angular 1.x, you could bind ngModel to a model for a select control:

<select ng-model="selectedPerson" 
   ng-options="person as person.name for person in people">
</select>

When an option is selected, the selectedPerson model will point to the person model that the user selected.

Is there a way to do the same thing in Angular2?

I've tried the following with no luck:

<select [(ngModel)] = "selectedPerson"> 
     <option *ngFor="#person of people"> {{ person.name }}</option>
</select>

I've also tried:

<select [(ngModel)] = "selectedPerson"> 
     <option *ngFor="#person of people" [value]="person"> {{ person.name }}</option>
</select>

In the first attempt, selectedPerson model references person.name rather than the person object. And in the second attempt, it is referencing an object, which doesn't appear to be a JSON object.

Any ideas what I am doing wrong? Is this even possible?

like image 273
pixelbits Avatar asked Dec 27 '15 05:12

pixelbits


1 Answers

You could implement a <select> inside a form using the FormBuilder directive:

import { FormBuilder, Validators } from '@angular/forms';

export class LoginPage {

  constructor(form: FormBuilder) {
    this.cities = ["Shimla", "New Delhi", "New York"]; // List of cities
    this.loginForm = form.group({
      username: ["", Validators.required],
      password: ["", Validators.required],
      city: ["", Validators.required] // Setting the field to "required"
    });
  }

  login(ev) {
    console.log(this.loginForm.value); // {username: <username>, password: <password>, city: <city>}
  }

}

In your .html:

<form [ngFormModel]="loginForm" (submit)="login($event)">

    <input type="text" ngControl="username">
    <input type="password" ngControl="password">
    <select ngControl="city">
        <option *ngFor="#c of cities" [value]="c">{{c}}</option>
    </select>
    <button block type="submit" [disabled]="!loginForm.valid">Submit</button>

</form>

Official Documentation

like image 127
Avijit Gupta Avatar answered Sep 25 '22 16:09

Avijit Gupta