使用ngModel为选择下拉菜单设置初始值 [英] setting initial value using ngModel for select dropdown

查看:61
本文介绍了使用ngModel为选择下拉菜单设置初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个tranTypes(事务类型)的数组,这些数组已加载到下拉列表中.用户选择一个值并在返回时导航到另一个组件后,在下拉菜单中未选择该值.

I have an array of tranTypes (transaction types) that are loaded into a dropdown. After the user selects a value and navigates to another component upon returning the value is not selected in the dropdown.

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

From other readings, I've learned this is b/c the objects are not the same instance. What do I do in this situation then?

<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 上,您可以使用自定义比较功能

From 4.0.0-beta.6 on, you can use a custom comparison function

<select [compareWith]="equals"

equals(o1: Country, o2: Country) {
   return o1.id === o2.id;
}

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

for earlier versions you can look up the tranType in tranTypes by comparing content similar to above equals, and then assign the found instance to model.tranType to make it the selected one.

这篇关于使用ngModel为选择下拉菜单设置初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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