【问题标题】:Ionic & Angular - ion-select null value is not recognizedIonic & Angular - 无法识别离子选择空值
【发布时间】:2019-11-26 11:41:58
【问题描述】:

通过渲染ion-select,我在 ionic 4 应用程序中遇到了 angular 8(包括反应形式)的问题:

不幸的是,我的null 值选项未被识别为ion-select 的选定值,即使离子选择的值(null)尽可能存在ion-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>

ion-select 上使用[placeholder] 作为空值的解决方法对我的方案没有用处,因为我希望null 选项仍然可供用户使用,即使有其他选项之前被选中。

这个问题有解决方案吗,还是我在结合 ionic4/reactive 形式时做错了什么?

【问题讨论】:

  • 另外:如果我只将类型的默认值设置为空字符串,则相应的选项将呈现为选中状态。 types[0].value = ''; - 但这也只是一种解决方法,在我看来并不是最终解决方案。
  • 出于好奇,你为什么不能这样尝试?公共类型 = [{value: 'all', title: 'All' },.....];而在构造函数中 this.formGroup = this.fb.group({ type: ['all'] });
  • @GangadharGandi 这将是一个可行的解决方案。但在我的场景中,我希望稍后 formGroup.getRawValue() 和表单提交具有 null 值,因为服务器 api 仅接受“所有类型”选项的 null 值。当然,我可以在提交表单之前轻松映射有效负载。
  • @GangadharGandi 没错,但这也是一种解决方法,而不是优雅的解决方案。
  • 好吧'null' 不是null。不等于null 的所有内容都只是一种解决方法。

标签: angular ionic-framework reactive-forms


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2018-01-22
    • 2020-07-17
    • 2019-06-13
    • 2020-12-17
    • 2020-01-11
    • 2018-10-23
    • 2020-05-29
    • 2019-05-30
    • 1970-01-01
    相关资源
    最近更新 更多