Binding select element to object in Angular

Component.ts file:

Component.ts file: 

@Component({
   selector: 'myApp',
   template: 'myApp.html'
})
export class AppComponent{
    countries = [
       {id: 1, name: "United States"},
       {id: 2, name: "Australia"}
       {id: 3, name: "Canada"},
       {id: 4, name: "Brazil"},
       {id: 5, name: "England"}
     ];
    selectedValue = null; //the current selected option id
}

Template:

<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.

Source: html – Binding select element to object in Angular – Stack Overflow

Leave a Reply