使用 ngModel 为 select 下拉菜单设置初始值

setting initial value using ngModel for select dropdown

我有一组 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;
}

早期版本可以在tranTypes中查找tranType类似上面equals的内容,然后将找到的实例赋值给model.tranType使其成为选中的.

您必须将变量 model.tranType 放置在由模型加载的服务中,该模型加载您正在导航的两个模型。这样你最终会得到一个单例服务,并且在你使用你的站点时变量将被保留。 这种方法的问题是,如果您刷新页面,服务将重新启动,您将再次选择默认选项。要解决这个问题,您必须将 model.tranType 变量状态保存在 localStorage 中,这样即使关闭浏览器,该选项也将保持不变。

您应该将绑定到 ngModel 的值与数组中对象的值完全相同。

<select [(ngModel)]="model.tranType">
 <option *ngFor="let type of tranTypes" [ngValue]="type.id">{{type.Desc}}</option>
</select>

最好使用 id 属性 作为 ngValue。

LIVE DEMO