two way data binding on select ngModel in Angular 5 when ngValue is object

Viewed 1291

I am using [(ngModel)] as a whole object. And this works fine when I do from scratch, but not when I use it in edit mode. So when, for example when I assign the ngModel via some other function, the select dropdown's view doesn't update. Here's how my HTML looks.

<select 
  class="form-control" 
  [(ngModel)]="selectedContentType" 
  [attr.disabled]="hideCollectionandContentType || hideContentTypeOnly ? '' : null" 
  required 
  (change)="contentTypeChanged(selectedContentType)">
  <option [ngValue]="undefined">
    Select Content Type
  </option>
  <option 
    *ngFor="let c of contentTypes" 
    [ngValue]="c">
    {{c.value}}
  </option>
</select>

The json for contentTypes looks like this format for each object.

{ key: '', value: ''}

For example, I am reading an existing form, which is supposed to display data coming from an API. I am setting the data back like this.

const selectedContentType = JSON.parse(res.BulkUpdate_SelectedContentType);
        this.selectedContentType = { key: selectedContentType.ContentTypeId, value: selectedContentType.ContentTypeName };

Its setting in the right format, but the select dropdown is not updating.

1 Answers

if you want to set the dropdown you have to set same object reference,object in javascript compare by reference and when you set selectedContentType to new object even if it 's has the same property and value it 's consider a different value.

this is a new object reference and it 's not eqale to any option value.

  this.selectedContentType = { key: selectedContentType.ContentTypeId, value: selectedContentType.ContentTypeName };

example

contentTypes = [
    {name:1,value:1},
    {name:2,value:2},
    {name:3,value:3},
    {name:4,value:4},
    ];

set() {
      // this.selectedContentType = {name:1,value:1}; // not working , new object refrences
      this.selectedContentType = this.contentTypes[0]; 
    }

if you want to set the selected item to value of 4 as an example

this.selectedContentType = this.contentTypes.find(i => i.value == 4);

in the line above we get the same object reference in the dropdown option list.

stackblitz demo

Related