Two-way binding for select element doesn't work properly | Angular 11

Issue

I have a JSON with structure:

For item

"item": {
        "pk": "123456",
        "title": "Title4",
        "list_fields": [
            {
                "pk": "12345",
                "title": "Selector",
                "type": "SEL",
                "position": 1,
                "locked": true,
                "value": {
                        "pk": 567,
                        "value": "Finished",
                        "position": 3,
                        "color": "FF0000"
                }
            }
        ]           
    },

For its selectors

"field": {
  "pk": "12345",
  "type": "SEL",
  "locked": true,
  "position": 1,
  "values": [
      {
          "pk": 123,
          "value": "Not Started",
          "position": 1,
          "color": "FF0000"
      },
      {
          "pk": 345,
          "value": "In Process",
          "position": 2,
          "color": "FF0000"
      },
      {
          "pk": 567,
          "value": "Finished",
          "position": 3,
          "color": "FF0000"
      }
    ]
}

So, I trying to make a simple selector, where I can see current list_fields values, that a part of field

    <ng-container *ngFor="let list_field of item.list_fields">

            <select [(ngModel)]="list_field.value" [name]="list_field.pk" [id]="list_field.pk">
                <option disabled>Select value</option>
                <option *ngFor="let val of field.values" [ngValue]="val">{{ val.value }}</option>
            </select>
        
    </ng-container>

When I made this selector, I got issue: when page loads, selector is empty (looks like, current value doest bind to select element via [(ngModel)])

selector is empty, but item have initial value

But when I start to select value from select dropdown, selected value bind to item with no problem.

What am I need to do to bind CURRENT value to selector, when page loads?

Solution

if you use ngValue as the value of the option this mean you need to set list_field.value as one of the field.values object because the selected value compared base of object reference

ngOnInit(){
this.field.value = this.field.values[2];
}

stackblitz demo 🚀

Answered By – Muhammed Albarmavi

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.