简体   繁体   中英

How to make mat-select first option null?

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

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];

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.

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.

Edit:

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;

in the template:

<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.

EDIT: 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.

Updated StackBlitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM