Binding select element to object in Angular Binding select element to object in Angular angular angular

Binding select element to object in Angular


<h1>My Application</h1><select [(ngModel)]="selectedValue">  <option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option></select>

StackBlitz example

NOTE: you can use [ngValue]="c" instead of [ngValue]="c.id" where c is the complete country object.

[value]="..." only supports string values
[ngValue]="..." supports any type

update

If the value is an object, the preselected instance needs to be identical with one of the values.

See also the recently added custom comparison https://github.com/angular/angular/issues/13268available since 4.0.0-beta.7

<select [compareWith]="compareFn" ...

Take care of if you want to access this within compareFn.

compareFn = this._compareFn.bind(this);// or // compareFn = (a, b) => this._compareFn(a, b);_compareFn(a, b) {   // Handle compare logic (eg check if unique ids are the same)   return a.id === b.id;}


This could help:

    <select [(ngModel)]="selectedValue">          <option *ngFor="#c of countries" [value]="c.id">{{c.name}}</option>    </select>


You can do this too without the need to use [(ngModel)] in your <select> tag

Declare a variable in your ts file

toStr = JSON.stringify;

and in you template do this

 <option *ngFor="let v of values;" [value]="toStr(v)">      {{v}} </option>

and then use

let value=JSON.parse(event.target.value)

to parse the string back into a valid JavaScript object