typescript 角形材料日期选择器-仅限月份和年份

xam8gpfp  于 2023-02-10  发布在  TypeScript
关注(0)|答案(7)|浏览(143)

我希望我的角材料日期选择器只显示月/年。没有天。
这是我的约会选择器:

<mat-form-field>
    <input matInput [matDatepicker]="picker" placeholder="Choose a date">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

我看到以前的线程声明将模式设置为:

md-mode="month"

以上都不行了,现在怎么解决?

1hdlvixo

1hdlvixo1#

这里有一个代码,为我工作。我看到你正在尝试类似的东西。希望它能有所帮助。
.html文件:

<mat-form-field>
    <input matInput [matDatepicker]="dp2" [min]="sixMonthsAgo" [max]="today" placeholder="Select a Date" (click)="openDatePicker(dp2)">
    <mat-datepicker-toggle matSuffix [for]="dp2"></mat-datepicker-toggle>
    <mat-datepicker #dp2 startView="multi-year" (monthSelected)="closeDatePicker($event, dp2)"></mat-datepicker>
  </mat-form-field>

来自.ts文件的代码段:

this.today = new Date();
  this.sixMonthsAgo = new Date();
  this.sixMonthsAgo.setMonth(this.today.getMonth() - 6);

  openDatePicker(dp) {
    dp.open();
  }

  closeDatePicker(eventData: any, dp?:any) {
    // get month and year from eventData and close datepicker, thus not allowing user to select date
    dp.close();    
  }
wwwo4jvm

wwwo4jvm2#

要求是在输入元素上显示"MMMM YYYY"格式。"MMMM YYYY"格式是"月年"。希望创建自定义日期格式并应用于mat-datepicker。
在HTML中

<mat-label>For the Month</mat-label>
<input matInput [matDatepicker]="picker1" name="CalMonth" formControlName="CalMonth">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1 disabled="false"></mat-datepicker>

在. ts typescript 中
我想导入材料-力矩-适配器材料/芯件力矩
安装材料力矩适配器
npm i@角/材料力矩适配器
npm i角力矩

import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import * as moment from 'moment';

export const MY_FORMATS = {
  parse: {
    dateInput: 'LL', 
  },
  display: {
    dateInput: 'MMMM YYYY', // this is the format showing on the input element
    monthYearLabel: 'MMMM YYYY', // this is showing on the calendar 
  },
};

然后添加到组件中

@Component({
  selector: 'app-monthselector',
  templateUrl: './monthselector.component.html',
  styleUrls: ['./monthselector.component.scss'],
  providers: [
    {
      provide: DateAdapter,
      useClass: MomentDateAdapter,
      deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
    },

    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],
})

然后将格式添加到相关控制器

this.UIForm = new FormGroup({
      CalMonth: new FormControl(moment()),
    });

按照上述步骤逐一操作,您可以自定义日期格式为**"Month Year"**。
你可以改变任何其他日期格式,只有改变这一点

    • 日期输入:'年-月-日',**

谢谢你,
英迪拉·普拉迪普

piok6c0g

piok6c0g3#

我完全依赖于官方Angular 材料文档中给出的示例,制定了一个解决方案:
https://material.angular.io/components/datepicker/overview#watching-the-views-for-changes-on-selected-years-and-months
代码示例运行良好,但当用户单击标题中的年份时,日历中仍存在"月份"视图的导航

以下是一个转折点:在自定义组件的TS中,其中
<mat-datepicker #dp startView="multi-year" (yearSelected)="chosenYearHandler($event)" (monthSelected)="chosenMonthHandler($event, datePicker)"></mat-datepicker>
在"角形材质"链接中声明为,我将添加:

@ViewChild('datePicker') public dp;

ngAfterViewInit(): void {
  this.dp.openedStream.subscribe(async _ => {
    while (this.dp._popupComponentRef.instance._calendar == null)
      await this.__delay__(100)

    this.dp._popupComponentRef.instance._calendar._calendarHeaderPortal._attachedHost._attachedRef.instance.currentPeriodClicked = function () {        
    
        // redefine here calendar navigation in header
        
        if (this.calendar.currentView == 'month')
            this.calendar.currentView = 'year'
        
        this.calendar.currentView = this.calendar.currentView == 'year' ? 'multi-year' : 'year';
    }
  })
}

这样您就可以自定义标题中的导航...

myzjeezk

myzjeezk4#

您可以使用这两个处理程序(chosenYearHandlerchosenMonthHandler),以及只显示月份和年份的格式:

TS:

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import {MatDatepicker} from '@angular/material/datepicker';

// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
import * as _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment, Moment} from 'moment';

const moment = _rollupMoment || _moment;

// See the Moment.js docs for the meaning of these formats:
// https://momentjs.com/docs/#/displaying/format/
export const MY_FORMATS = {
  parse: {
    dateInput: 'MM/YYYY',
  },
  display: {
    dateInput: 'MM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

/** @title Datepicker emulating a Year and month picker */
@Component({
  selector: 'datepicker-views-selection-example',
  templateUrl: 'datepicker-views-selection-example.html',
  styleUrls: ['datepicker-views-selection-example.css'],
  providers: [
    // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your
    // application's root module. We provide it at the component level here, due to limitations of
    // our example generation script.
    {
      provide: DateAdapter,
      useClass: MomentDateAdapter,
      deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
    },

    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],
})
export class DatepickerViewsSelectionExample {
  date = new FormControl(moment());

  chosenYearHandler(normalizedYear: Moment) {
    const ctrlValue = this.date.value;
    ctrlValue.year(normalizedYear.year());
    this.date.setValue(ctrlValue);
  }

  chosenMonthHandler(normalizedMonth: Moment, datepicker: MatDatepicker<Moment>) {
    const ctrlValue = this.date.value;
    ctrlValue.month(normalizedMonth.month());
    this.date.setValue(ctrlValue);
    datepicker.close();
  }
}

超文本标记语言:

<mat-form-field appearance="fill">
  <mat-label>Month and Year</mat-label>
  <input matInput [matDatepicker]="dp" [formControl]="date">
  <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
  <mat-datepicker #dp
                  startView="multi-year"
                  (yearSelected)="chosenYearHandler($event)"
                  (monthSelected)="chosenMonthHandler($event, dp)"
                  panelClass="example-month-picker">
  </mat-datepicker>
</mat-form-field>

中央支助组:

.example-month-picker .mat-calendar-period-button {
  pointer-events: none;
}

.example-month-picker .mat-calendar-arrow {
  display: none;
}

更多解释:https://material.angular.io/components/datepicker/examples

olhwl3o2

olhwl3o26#

.html格式的代码

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

代码单位.ts

import {MatDatepicker} from '@angular/material/datepicker';

 @ViewChild('picker') datePickerElement = MatDatepicker;

  ngOnInit() {
    console.log(this.datePickerElement) 
    console.log(this.datePickerElement['opened'])  
   
    setTimeout(() => {
          this.datePickerElement['_datepickerInput']._dateFormats = {
  parse: {
    dateInput: 'LL', 
  },
  display: {
    dateInput: 'MMMM YYYY',
    monthYearLabel: 'MMMM YYYY', 
  },
};
    },1000)

  }

这对我来说很好。日期格式将显示如下截图

mbzjlibv

mbzjlibv7#

在我的例子中,我有一个动态的输入量,所以我不能像文档中那样将数据插入表单控件:https://material.angular.io/components/datepicker/overview#datepicker-views-selection
这就是我的解决方案:

setDateHandler(dateEvent: Moment,datepicker: MatDatepicker<any>) {
datepicker._selectedChanged.next(dateEvent);
datepicker.close(); }

相关问题