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}]
4
  • Possible duplicate of Angular Reactive Forms: Dynamic Select dropdown value not binding Commented Apr 6, 2018 at 9: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 Commented Apr 6, 2018 at 9:59
  • 1
    can you post your current data of fiterViewData. Departments and filter. Department? So we can see what's the difference. Commented Apr 6, 2018 at 10:17
  • @Pengyy I have updated JSON data Commented Apr 6, 2018 at 11:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You nailed it.. It was a typo i copied the code which has compareFn but I ignored to see.. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.