如何设置离子选项的默认选择值? [英] How to set default selected value of ion-option?

查看:43
本文介绍了如何设置离子选项的默认选择值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Ionic v2,但在显示页面时无法设置所选值.

I'm using Ionic v2 and I can not set the selected value when showing the page.

<ion-select [(ngModel)]="company.form">
    <ion-option *ngFor="let form of forms" [value]="form" [selected]="true">{{form.name}}</ion-option>
</ion-select>

我也试过 checked ,但这也行不通.我怎样才能做到这一点?

I've tried with checked, too but that isn't work either. How can I do this?

Cordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.1.13
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 0.0.45

推荐答案

如果您处理默认值 xor 对象,最简洁的方法是为 [compareWith] 属性提供一个比较函数.此函数在参数中接受 2 个对象,如果它们相等则返回 true.这样,模型中的现有值将在开始时被选择.如果在选择之外的模型中添加新数据,这也适用.

If you deal with default value xor objects, the cleanest way is to provide a compare function to the [compareWith] attribute. This function takes 2 objects in parameters and returns true if they are equals. This way, existing values in model will be selected at start. This works too if new data are added in model outside of the select.

以下示例取自官方 Ionic 文档

Following example is taken from official Ionic doc

<ion-item>
  <ion-label>Employee</ion-label>
  <ion-select [(ngModel)]="employee" [compareWith]="compareFn">
    <ion-option *ngFor="let employee of employees" [value]="employee"></ion-option>
  </ion-select>
</ion-item>

compareFn(e1: Employee, e2: Employee): boolean {
  return e1 && e2 ? e1.id == e2.id : e1 == e2;
}

使用双等号使其适用于 Ionic 4(正如 Stan Kurdziel 在评论中建议的那样)

EDIT : using double equals make it work for Ionic 4 (as Stan Kurdziel suggests in comment)

这篇关于如何设置离子选项的默认选择值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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