如何使垫选择第一个选项为空? [英] How to make mat-select first option null?

查看:65
本文介绍了如何使垫选择第一个选项为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用3个 mat-select 进行日-月-年选择,如此

I use 3 mat-select for day-month-year selection as shown on this DEMO.

我需要将第一个选项设置为null或undefined,并如下所示修改该代码:

I need to make the first options as null or undefined and modify that code as shown below:

allDates: number[] = [null];
dates: number[] = [null];
months: number[] = [null];
years: number[] = [null];

但是我不确定这是个好主意还是 mat-select 的正确方法.我还尝试为 mat-select 选项设置 [value] = null ,但是在这种情况下,它不能正确接收该值.那么,什么是正确的方法呢?

But I am not sure if it is a good idea or is there a proper way for mat-select. I also try to set [value]=null for the mat-select options, but in that case it does not receive the value properly. So, what is a proper way for this?

推荐答案

是否有必要将它们设置为空的原因?在我看来,有一个空白选项会更加令人困惑.

Is there a reason they need to be null? In my opinion it is more confusing to have a blank option.

试玩一下堆栈闪电,以查看它初始化为空数组时的行为以及将其绑定到具有一个空项目的数组时的行为.我认为当mat-select绑定到一个空数组时,UX很棒.垫标签位于选择框中,可轻松查看选择中的数据类型.同样,当您单击它时,它不会显示任何选项,因为没有任何选项.如果为空,则下拉列表将打开,其中包含一个空白项目.

Play around with the stack blitz to see how it behaves when initialized as an empty array vs when it is bound to an array with one null item. I think the UX is great when the mat-select is bound to an empty array. The mat-label resides in the select box, easy to see what type of data is in the select. Also when you click it, it doesn't show any options, because there aren't any. If you have a null, then the dropdown opens with one blank item.

我认为您提供的代码没有任何问题.

I don't think there is anything wrong with the code you provided.

您可以将Mat-select项与一个对象绑定,并使用display属性显示文本,并使用value属性绑定到实际值.

You can bind the mat-select item with an object and use a display property to show the text and a value property to bind to the actual value.

假设您有一个这样的界面:

Say you have an interface like this:

export interface DateSelectItem
{
    value: number;
    label: string;
}

let dates: DateSelectItem[] = [
    {
        value: -1
        label: "None"
    }
];

selectedDate: DateSelectItem;

在模板中:

<mat-form-field>
  <mat-label>Date</mat-label>
  <mat-select [(ngModel)]="selectedDate">
    <mat-option *ngFor="let date of dates" [value]="date">
      {{date.label}}
    </mat-option>
  </mat-select>
</mat-form-field>

您可以只使用字符串,并使用等价的数字来回转换它们.

You can use just strings and convert them back and forth with their number equivalents.

或者,如果您使用对象,则可以使用label属性显示值以外的其他内容.

Or if you use an object you can use the label property to display something other than the value.

修改后的StackBlitz

Modified StackBlitz

如果用户在当月的某天中选择无",您可能需要更新业务逻辑,以使最终日期看起来像什么.

You will probably need to update the business logic on what you want the resulting date to look like if the user selects 'None' for day-of-the-month.

更新了StackBlitz

这篇关于如何使垫选择第一个选项为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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