【问题标题】:Angular Material 6 datepicker different formats in same componentAngular Material 6 datepicker在同一组件中的不同格式
【发布时间】:2018-10-06 09:45:13
【问题描述】:

我需要在一个组件视图的两个 mat datepicker 字段中选择两种不同的日期格式(YYYY-MM-DD 和 YYYY-MM)。

我正在使用角度 6.0.3 和材质 6.4.7。

我在应用程序模块中使用 MAT_DATE_FORMATS 将日期选择器格式配置为 YYYY-MM-DD,它可以在全局范围内使用,但我需要在上面写的几个日期选择器字段中将此格式覆盖为 YYYY-MM。 不幸的是,我不知道如何实现这一目标。

你能帮帮我吗?

我的部分代码:

        import { Component, OnInit, ViewChild } from '@angular/core';
    import { FormGroup, FormControl } from '@angular/forms';

    @Component({
      selector: 'app-invoice-list',
      templateUrl: './invoice-list.component.html',
      styleUrls: ['./invoice-list.component.css']
    })
    export class InvoiceListComponent {

      filterForm: FormGroup;

      @ViewChild('month_picker') month_picker;

      constructor() {
        this.filterForm = new FormGroup({
          assigned_date_from: new FormControl(),
          assigned_date_to: new FormControl(),
          assigned_month: new FormControl(),
        });
      }
    }

<div class="container" [formGroup]="filterForm">
  <div class="container" fxLayout="row" fxLayout.xs="column" fxLayoutWrap fxLayoutGap="0.5%" fxLayoutAlign="start">
      <div fxFlex="32%">
        <mat-form-field>
            <input matInput [matDatepicker]="date_from_picker" (focus)="date_from_picker.open()" formControlName="assigned_date_from" placeholder="Date from">
            <mat-datepicker-toggle matSuffix [for]="date_from_picker"></mat-datepicker-toggle>
            <mat-datepicker #date_from_picker></mat-datepicker>
        </mat-form-field>
      </div>
      <div fxFlex="32%">
        <mat-form-field>
            <input matInput [matDatepicker]="date_to_picker" (focus)="date_to_picker.open()" formControlName="assigned_date_to" placeholder="Date to">
            <mat-datepicker-toggle matSuffix [for]="date_to_picker"></mat-datepicker-toggle>
            <mat-datepicker #date_to_picker></mat-datepicker>
          </mat-form-field>
      </div>

      <!-- In below input I want month year format - YYYY-MM - so different than default format in above fields -->
      <div fxFlex="32%">
          <mat-form-field>
              <input matInput [matDatepicker]="month_picker" (focus)="month_picker.open()" formControlName="assigned_month" placeholder="Month">
              <mat-datepicker-toggle matSuffix [for]="month_picker"></mat-datepicker-toggle>
              <mat-datepicker #month_picker></mat-datepicker>
            </mat-form-field>
        </div>
    </div>
</div>

【问题讨论】:

  • 你不能使用 viewChild 吗?
  • 我考虑过 viewChild,但 viewChild 变量是为我视图中的所有日期选择器共享的,对吧?这样,此日期选择器(viewChild 变量)上组件的所有更改都将应用于我视图中的所有日期选择器字段
  • 不,我可以帮你,但我需要一些时间。你能把你的 html 和 ts 文件放上去吗。
  • 谢谢!!我在帖子中添加了部分代码
  • 无需添加viewChildren。我会发布我的答案

标签: angular datepicker angular-material


【解决方案1】:

请试试这个。 在你的 HTML 中

        <mat-form-field>
          <input matInput [matDatepicker]="month_picker" (focus)="month_picker.open()" [value] = "selectedMonth" placeholder="Month">
          <mat-datepicker-toggle matSuffix [for]="month_picker"></mat-datepicker-toggle>
          <mat-datepicker #month_picker  
              startView="multi-year"
              (monthSelected)="chosenMonthHandler($event, month_picker)"></mat-datepicker>
        </mat-form-field>

在您的 .ts 中

    selectedMonth = new Date();

    chosenMonthHandler(normlizedMonth, datepicker) {
        var tempDate = JSON.stringify(normlizedMonth).replace("\"",'').split("-")
        var month = parseInt(tempDate[1])
        var year = month == 12?parseInt(tempDate[0])+1:parseInt(tempDate[0])
        var year = month == 12?parseInt(tempDate[0])+1:parseInt(tempDate[0])
        month = month == 12?1:month+1;
        this.selectedMonth = new Date(year + "-" + month)
        console.log(year + " " + month)
        datepicker.close();
      }

这很好用。但是在选择一个月后将所选日期显示为 1。但我认为这满足您的要求。

【讨论】:

  • 我已经尝试过了,但它不起作用。当我打开日期选择器时开始查看月份列表,但是当我选择月份时,有一天可以选择,最后日期以我的全局格式显示:(
  • 啊,我在找那个。这是一项艰苦的工作,但我会为你做的。
  • Asanka 非常感谢您!我会简化从 normalizeMonth 变量获取日期: normlizedMonth.format('YYYY-MM');因为 normalizedMonth 是时刻对象。少了几行代码 :) 顺便说一句,我有一个小问题——如果我在几个地方/组件中使用这个函数(chosenMonthHandler),你建议在什么地方存储这个函数(chosenMonthHandler)。有什么服务吗?这方面的最佳做法是什么?
【解决方案2】:
  1. 如果您正在寻找一种拥有几种静态格式的方法,那就是 possible.

    不幸的是,如果你想让它基于一个动态的 指令输入(例如)这不会 工作,因为目前没有机制告诉 格式已更新的日期选择器。

    更多信息可以找到here

【讨论】:

    【解决方案3】:
    http://brickydev.com/angular-material-datepicker-with-many-custom-date-formats/
    

    我找到了这个链接,这个解决方案对我有用。

    第 1 步:创建指令

    ng generate directive customDateFormat
    

    第 2 步:

    import { Directive } from '@angular/core';
    import { MAT_DATE_FORMATS } from '@angular/material/core';
    
    export const FORMAT = {
      parse: {
        dateInput: 'DD-MM-YYYY',
      },
      display: {
        dateInput: 'DD-MM-YYYY',
        monthYearLabel: 'MMM YYYY',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM YYYY',
      },
    };
    
    @Directive({
      selector: '[appCustomeDateFormats]',
      providers: [{ provide: MAT_DATE_FORMATS, useValue: FORMAT }],
    })
    export class CustomeDateFormatsDirective {
      constructor() {}
    }
    

    第 3 步:在模板中使用此指令。

         <mat-form-field class="example-full-width" appCustomeDateFormats>
                <mat-label>Start Date</mat-label>
                <input
                  matInput
                  [matDatepicker]="startDate"
                  formControlName="from_date"
                />
                <mat-datepicker-toggle
                  matSuffix
                  [for]="startDate"
                ></mat-datepicker-toggle>
                <mat-datepicker touchUi #startDate></mat-datepicker>
              </mat-form-field>
    

    【讨论】:

      猜你喜欢
      • 2021-11-05
      • 2019-05-12
      • 2019-08-17
      • 2020-01-27
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      相关资源
      最近更新 更多