首页 > 解决方案 > Ionic & Angular - 无法识别离子选择空值

问题描述

我的 ionic 4 应用程序中存在 angular 8(包括反应形式)的问题,方法是渲染ion-select

不幸的是,即使离子选择的值(null)尽可能存在,我的null值选项也不会被识别为选定值。ion-selection-select-option

我的组件如下所示:

export class MyComponent {
    public formGroup;
    public types = [
        {
            value: null,
            title: 'All'
        },
        {
            value: 'Type-1',
            title: 'Type 1'
        },
        {
            value: 'Type-2',
            title: 'Type 2'
        }
    ];

    constructor(private fb: FormBuilder) {
        this.formGroup = this.fb.group({
            type: [null]
        });
    }
}

该组件的模板如下所示:

<ion-content>
    <form [formGroup]="formGroup">
        <ion-list>
            <ion-item>
              <ion-label position="floating">Type</ion-label>
              <ion-select formControlName="type" interface="popover">
                <ion-select-option *ngFor="let type of types" [value]="type.value">
                  {{ type.title }}
                </ion-select-option>
              </ion-select>
            </ion-item>
        </ion-list>
    </form>
</ion-content>

[placeholder]通过在 null 值上使用 a 的解决方法ion-select对我的方案没有用,因为即使之前选择了其他选项,我也希望该null选项仍然可供用户使用。

有没有解决这个问题的方法,或者我在结合 ionic4/reactive 形式时做错了什么?

标签: angularionic-frameworkreactive-forms

解决方案


我有同样的问题,我尝试了使用 compareWith 函数的解决方法:

<ion-select ... [compareWith]="compareWithFn">

public compareWithFn(value1, value2) {
    // value1 option value, value2 - control value
    if (value1 === null && !value2) {
        return true;
    }
    return value1 === value2;
}

这帮助我选择了“全部”选项。


推荐阅读