Tamas Koos
Tamas Koos

Reputation: 63

Bind value to html select

I try to bind value to an html select. It works great except when the value is already set, it doesn't get selected in the select.

<div class="col-md-1">
      <label class="search-label">{{'AUDIT_LOG_SEARCH_METHOD_DEVICE_TYPE' | translate}}</label>
      <select class="form-control" [(ngModel)]="searchModel.request_device_type"
              id="device_id" name="device_id" #device_id="ngModel">
        <option *ngFor="let item of auditLogDeviceTypeItems" [ngValue]="item">{{item.text}}</option>
      </select>
    </div>

What am I doing wrong?

Upvotes: 0

Views: 404

Answers (2)

iatsi
iatsi

Reputation: 151

<div class="col-md-1">
      <label class="search-label">{{'AUDIT_LOG_SEARCH_METHOD_DEVICE_TYPE' | translate}}</label>
      <select class="form-control id="device_id" name="device_id" #device_id="ngModel">
        <option *ngFor="let item of auditLogDeviceTypeItems" [ngValue]="item" [selected]="searchModel.request_device_type == item">{{item.text}}</option>
      </select>
    </div>

Since you have not provided with the complete data structure that resides in variable, this is the solution I can think of. Please tweak it as per your requirement.

Upvotes: 1

Krishna Rathore
Krishna Rathore

Reputation: 9687

You can try with this solution.

I have create a demo on Stackblitz

use [compareWith]="compareObjects" for use object in select

component.html

<select name="role" [compareWith]="compareObjects" [(ngModel)]="searchModel.request_device_type">
    <option *ngFor="let r of auditLogDeviceTypeItems" [ngValue]="r">{{r.name}}</option>
</select>

component.ts

  searchModel = {
    request_device_type: { "id": 1, "name": "user" }
  }
  auditLogDeviceTypeItems = [
    { "id": 1, "name": "user" }, 
    { "id": 2, "name": "admin" }
  ]

  compareObjects(o1: any, o2: any): boolean {
    return o1.id === o2.id && o1.name === o2.name;
  }

Upvotes: 0

Related Questions