首页 > 解决方案 > Angular Material Datepicker - 首先选择月份,然后选择第二个年份

问题描述

我正在做一个角度项目,我正在寻找一种方法来使角度材料日期选择器更改为先选择月份,然后选择第二年(不需要天)。

这是我当前的代码:

例子.component.ts


    import { of } from 'rxjs';

    public isMonthOpened = true;

    public chosenMonthHandler(normalizedMonth: moment.Moment, datepicker: MatDatepicker<moment.Moment>, dateFormControl: FormControl, date: Date): void {
        normalizedMonth = moment(normalizedMonth);
        const ctrlValue = dateFormControl.value;
        ctrlValue.month(normalizedMonth.month());
        dateFormControl.setValue(moment(ctrlValue));
        this.isMonthOpened = false;
        date.setMonth(ctrlValue.toDate().getMonth());
        // the datepicker does not re-open after closing if I do not set a delay
        of(datepicker.close()).subscribe(() => {
            setTimeout(() => {
                datepicker.open();
            }, 250);
        });
    }
    
    public chosenYearHandler(normalizedYear: moment.Moment, datepicker: MatDatepicker<moment.Moment>, dateFormControl: FormControl, date: Date): void {
        normalizedYear = moment(normalizedYear);
        const ctrlValue = moment(dateFormControl.value);
        ctrlValue.year(normalizedYear.year());
        dateFormControl.setValue(ctrlValue);
        datepicker.close();
        date.setFullYear(ctrlValue.toDate().getFullYear());
        this.isMonthOpened = true;
    }

example.component.html

    <mat-form-field appearance="outline" class="custom-form-field" (click)="startDP.open()">
        <mat-label>Start</mat-label>
        <input matInput [matDatepicker]="startDP" #startDPInput [formControl]="startDateFormControl" />
        <mat-datepicker-toggle matSuffix [for]="startDP"></mat-datepicker-toggle>
        <mat-datepicker
            #startDP
            [startView]="isMonthOpened ? 'year' : 'multi-year'"
            (yearSelected)="chosenYearHandler($event, startDP, startDateFormControl, _startDate)"
            (monthSelected)="chosenMonthHandler($event, startDP, startDateFormControl, _startDate)"
        >
        </mat-datepicker>
    </mat-form-field>

有没有更好的方法来做到这一点?

标签: angularangular-materialdatepicker

解决方案


推荐阅读