角度选择默认值显示为空

时间:2018-04-06 09:36:03

标签: angular select

我正在开发Angular 4应用程序,它具有填充默认值的下拉列表。但我的下面的代码不适用于default选择。无论我通过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> 

我已经仔细检查了json数据,看起来很好。这是截图

enter image description here

已经尝试Angular 2 Dropdown Options Default Value但没有任何作用。不知道是什么问题,整天我都无法弄清楚原因。

以下是json数据:

过滤器。系

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

fiterViewData。部门

[{"DepartmentId":400,"Name":"IT","IsActive":true},   
{"DepartmentId":401,"Name":"Transport","IsActive":true},
{"DepartmentId":402,"Name":"Admin","IsActive":true}]

1 个答案:

答案 0 :(得分:1)

在将对象绑定到选项的选项时,compareWith会使ngModel值与选项的值匹配变得很简单,即使它们保持不同的实例(你当前问题的原因。)

模板:

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

成分:

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

参考 demo