1

I am developing Angular 4 Application, which have a dropdown with a default value populated. But my below code is not working for default selection. It shows blank regardless of what I set via ngModel.

<div class="form-group form-ctrl-display header-button-align">
  <select name="selectDepartment" class="form-control form-control-sm"
    [class.faded]="format.isEmpty(filter.Department)"
    style="max-width: 94px"
    [(ngModel)]="filter.Department"
    placeholder="Department">

    <option *ngFor="let department of filterViewData.Departments"
      [ngValue]="department">
      {{department.Name}}
    </option>
  </select>
  {{filter.Department| json}}
</div> 

I have double checked the json data and it looks Ok. Here is the screenshot

enter image description here

Already tried Angular 2 Dropdown Options Default Value but nothing works. Not sure what is the problem and whole day I cant figure out the reason.

Below is the json data:

filter. Department

{"DepartmentId":401,"Name":"Transport","IsActive":true}

fiterViewData. Departments

[{"DepartmentId":400,"Name":"IT","IsActive":true},   
{"DepartmentId":401,"Name":"Transport","IsActive":true},
{"DepartmentId":402,"Name":"Admin","IsActive":true}]
Pengyy
  • 37,383
  • 15
  • 83
  • 73
Developer
  • 487
  • 9
  • 28
  • Possible duplicate of [Angular Reactive Forms: Dynamic Select dropdown value not binding](https://stackoverflow.com/questions/46164708/angular-reactive-forms-dynamic-select-dropdown-value-not-binding) – Pengyy Apr 06 '18 at 09:41
  • 1
    @Pengyy its not a reactive form and not adding any dynamic controls. All static with the data populated on server. I am not constructing form in component.ts. I tried with compareWith option, this also doesnt work – Developer Apr 06 '18 at 09:59
  • 1
    can you post your current data of `fiterViewData. Departments ` and `filter. Department`? So we can see what's the difference. – Pengyy Apr 06 '18 at 10:17
  • @Pengyy I have updated JSON data – Developer Apr 06 '18 at 11:00

1 Answers1

1

While binding object to options of select, compareWith will make it simple to match ngModel value with option's value even when they keep different instances(the reason to your current problem).

template:

<select [(ngModel)]="filter.Department" [compareWith]="compareFun">
  <option *ngFor="let department of filterViewData.Departments"
    [ngValue]="department">
    {{department.Name}}
  </option>
</select>

component:

compareFun(item1, item2) {
  // you can determine the rule of matching different objects(for example: DepartmentId)
  return item1 && item2 ? item1.DepartmentId === item2.DepartmentId : item1 === item2;
}

refer demo.

Pengyy
  • 37,383
  • 15
  • 83
  • 73