角度选择默认值显示为空 [英] Angular Select default value shows empty

查看:76
本文介绍了角度选择默认值显示为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Angular 4应用程序,该应用程序的下拉列表中已填充默认值.但是我下面的代码不适用于default选择.无论我通过ngModel设置了什么,它都会显示为空白.

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> 

我已经仔细检查了json数据,看起来还可以.这是屏幕截图

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

已经尝试过 Angular 2下拉选项默认值,但没有任何效果.不知道是什么问题,我整天都无法找出原因.

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.

以下是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}]

推荐答案

虽然将对象绑定到select选项,但是compareWith将使ngModel值与选项值的匹配变得简单,即使它们保留不同的实例(当前问题的原因).

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).

模板:

<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;
}

引用 演示 .

refer demo.

这篇关于角度选择默认值显示为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆