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

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

问题描述

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

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 绑定到一个空数组时,用户体验很棒.mat-label 位于选择框中,便于查看选择中的数据类型.此外,当您单击它时,它不会显示任何选项,因为没有任何选项.如果您有一个空值,那么下拉菜单会打开一个空白项目.

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.

或者,如果您使用对象,您可以使用标签属性来显示值以外的内容.

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

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

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