加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 使用ngModel为选择下拉列表设置初始值

发布时间:2020-12-17 07:55:07 所属栏目:安全 来源:网络整理
导读:我有一个tranTypes(事务类型)数组加载到下拉列表中.在用户选择值并在返回时导航到另一个组件之后,未在下拉列表中选择该值. 从其他读物中,我了解到这是b / c对象不是同一个实例.那么在这种情况下我该怎么办? select name="tranType" class="form-control" [(
我有一个tranTypes(事务类型)数组加载到下拉列表中.在用户选择值并在返回时导航到另一个组件之后,未在下拉列表中选择该值.

从其他读物中,我了解到这是b / c对象不是同一个实例.那么在这种情况下我该怎么办?

<select name="tranType"
    class="form-control"
    [(ngModel)]="model.tranType"
    required>
   <option *ngFor="let tranType of tranTypes"
     [ngValue]="tranType">{{tranType.desc}}</option>
 </select>

ngOnInit(): void {
    this.myService.getTranTypes()
        .subscribe(tranTypes => {
            this.tranTypes = tranTypes;
            //set value of tranType if already set in the model
            if (this.myService.model.tranType != undefined) {
                this.myService.model.tranType = this.tranTypes.find(r => r.id == this.myService.model.tranType.id);
            }
        },error => this.errorMessage = <any>error);
}
从 4.0.0-beta.6开始,您可以使用自定义比较功能
<select [compareWith]="equals"
equals(o1: Country,o2: Country) {
   return o1.id === o2.id;
}

对于早期版本,您可以通过比较类似于上面等于的内容来查找tranType中的tranType,然后将找到的实例分配给model.tranType以使其成为选定的实例.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读