Binding select element to object in Angular

angular select
angular 6 select options example
angular 6 select option selected value
can't bind to 'ngmodel' since it isn't a known property of 'select'
angular select on change
angular select option
angular 4 select options example
angular bind object to element

I'd like to bind a select element to a list of objects -- which is easy enough:

@Component({
   selector: 'myApp',
   template: `<h1>My Application</h1>
              <select [(ngModel)]="selectedValue">
                 <option *ngFor="#c of countries" value="c.id">{{c.name}}</option>
              </select>`
})
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;
}

In this case, it appears that selectedValue would be a number -- the id of the selected item.

However, I'd actually like to bind to the country object itself so that selectedValue is the object rather than just the id. I tried changing the value of the option like so:

<option *ngFor="#c of countries" value="c">{{c.name}}</option>

but this does not seem to work. It seems to place an object in my selectedValue -- but not the object that I'm expecting. You can see this in my Plunker example.

I also tried binding to the change event so that I could set the object myself based on the selected id; however, it appears that the change event fires before the bound ngModel is updated -- meaning I don't have access to the newly selected value at that point.

Is there a clean way to bind a select element to an object with Angular 2?

<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/13268 available 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;
}

How to bind Select element to object in Angular with examples , To bind select element to object in angular use [ngValue] property. We will go through an example to understand it further. we will create a  Last updated on Jan 15, 2020 1 min read. To bind select element to object in angular use [ngValue] property. We will go through an example to understand it further. we will create a component called BindSelectToObjectComponent in our angular project.

This could help:

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

Angular Bind Object to Select Element Example, Now, let's see tutorial of select box bind object in angular. you will learn angular select option binding object. you'll learn select option binding  In this article, we will implement a angular select element bind to object. you will learn bind select element to object in angular. In this article, we will implement a select box bind object in angular 6, angular 7, angular 8 and angular 9. Sometime we need to bind select element to object so when you run change event then you can easily get selected option object and perform some action on it.

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

Bind Select DropDown List in Angular 4 and 5, Earlier I posted about how to bind select dropdown list in Angular 2, but its <​option *ngFor="let summary of summaries" value={{summary}}>. Let's get started with Binding Select Element to Object in Angular. In this article, we will implement a select box bind object in angular 6, angular 7, angular 8 and angular 9. Sometime we need to bind select element to object so when you run change event then you can easily get selected option object and perform some action on it.

It worked for me:

Template HTML:

I added (ngModelChange)="selectChange($event)" to my select.

<div>
  <label for="myListOptions">My List Options</label>
  <select (ngModelChange)="selectChange($event)" [(ngModel)]=model.myListOptions.id >
    <option *ngFor="let oneOption of listOptions" [ngValue]="oneOption.id">{{oneOption.name}}</option>
  </select>
</div>

On component.ts:

  listOptions = [
    { id: 0, name: "Perfect" },
    { id: 1, name: "Low" },
    { id: 2, name: "Minor" },
    { id: 3, name: "High" },
  ];

An you need add to component.ts this function:

  selectChange( $event) {
    //In my case $event come with a id value
    this.model.myListOptions = this.listOptions[$event];
  }

Note: I try with [select]="oneOption.id==model.myListOptions.id" and not work.

============= Another ways can be: =========

Template HTML:

I added [compareWith]="compareByOptionId to my select.

<div>
  <label for="myListOptions">My List Options</label>
  <select [(ngModel)]=model.myListOptions [compareWith]="compareByOptionId">
    <option *ngFor="let oneOption of listOptions" [ngValue]="oneOption">{{oneOption.name}}</option>
  </select>
</div>

On component.ts:

  listOptions = [
    { id: 0, name: "Perfect" },
    { id: 1, name: "Low" },
    { id: 2, name: "Minor" },
    { id: 3, name: "High" },
  ];

An you need add to component.ts this function:

 /* Return true or false if it is the selected */
 compareByOptionId(idFist, idSecond) {
    return idFist && idSecond && idFist.id == idSecond.id;
 }

Using ngModel with select, Using ngModel with select Let's look at how select has been set up: We are using ngFor here to bind to an array, durations , which is in the Workout the array with the title for each item being displayed using interpolation, {{duration.​title}} . I also tried binding to the change event so that I could set the object myself based on the selected id; however, it appears that the change event fires before the bound ngModel is updated — meaning I don’t have access to the newly selected value at that point. Is there a clean way to bind a select element to an object with Angular 2?

Just in case someone is looking to do the same using Reactive Forms:

<form [formGroup]="form">
  <select formControlName="country">
    <option *ngFor="let country of countries" [ngValue]="country">{{country.name}}</option>
  </select>
  <p>Selected Country: {{country?.name}}</p>
</form>

Check the working example here

AngularJS: API: select, HTML select element with AngularJS data-binding. The select directive is used together Using ngValue to bind the model to an array of objects. Edit in Plunker​. Angular material provides <mat-select> is a form control for selecting a value from a set of options, similar to the native <select> element. You can read more about selects in the Material Design spec. It is designed to work inside of an <mat-form-field> element. We can add options to the select by adding <mat-option> elements to the <mat-select>.

ngOptions, When an item in the <select> menu is selected, the array element or object property represented by the selected option will be bound to the model identified by  The select directive is used together with ngModel to provide data-binding between the scope and the <select> control (including setting default values). It also handles dynamic <option> elements, which can be added using the ngRepeat or ngOptions directives. When an item in the <select> menu is selected, the value of the selected option will be bound to the model identified by the ngModel directive.

How to use select/option/NgFor on an array of objects? · Issue , I knew how to do it in AngularJS using ngOptions, but it doesn't seem 'Select Object via 2-way binding' was my attempt to use 2-way binding. In Angular, we can bind the data through Property binding. HTML elements have backing dom properties that track state on elements. You can use Angular’s property binding syntax to wire into those properties. You go this with a specific syntax—a pair of square brackets around a property name on an element. And you set these equal to a template expression.

Angular 2 Select Option + Multiple Select Option + Validation , In Angular select element, the value attribute of <option> element can bind an object using property binding and one field of the object can be  Let's get started with Binding Select Element to Object in Angular. In this article, we will implement a select box bind object in angular 6, angular 7, angular 8 and angular 9. Sometime we need to bind select element to object so when you run change event then you can easily get selected option object and perform some action on it.

Comments
  • Just realized my Plunk works a little differently in IE vs. Chrome. Neither one actually works the way I'm wanting, but FYI.
  • Tried it but this does seem to data-bind only from Dropdown to model. If entering the page with model already set the dropdown is not set accordingly...
  • @Strinder a frequent mistake is to use another object instance for selectedValue than for c of (the default item). A different object even with the same properties and values doesn't work, it has to be the same object instance.
  • @GünterZöchbauer Yeah. Already thought of thought. So there's no easy way to sync directly with model and a list of values? = always via onChange?
  • Soon we might be able to compare the ngModel objects by their property using custom comparator function. Just watch this issue: github.com/angular/angular/issues/13268
  • It's always easy once you know it ;-) but angular.io/api/forms/NgSelectOption#description contains a link angular.io/api/forms/SelectControlValueAccessor with good docs.
  • I've used [value] instead of [ngValue]. It's not the same. This worked for me
  • Error on '#' in angular 4
  • Use let instead of # @sea-kg
  • This answer doesn't get the selected value
  • This indeed is doable, but on large objects will become a pain. Also, Angular's underline capability of change detection is something to be thought of. Outputting information as json, easily parsable by bots, adds to performance hauls. Using Angular's change detection hides (encapsulates) the logic of the data, and assures you of your needed information. @Günter Zöchbauer answer is the way to do it in Angular. :)
  • Helped me where I had a single list and changing one value should not update the next so it helped using this as a hack without the use of ngmodel,Thanks :)
  • This works for plain JavaScript objects but note for instances of a class you'd lose all the methods on it.
  • This is good if you also want to handle the change event to do something extra (like inform a change callback). Though in that case, you only need to put [ngModel] and then set your model manually in your custom change callback defined in (ngModelChange).