首页 文章

Angular Material mat-datepicker(更改)事件和格式

提问于
浏览
6

我使用角度材料datepicker指令,我有几个问题 .

1. 当我打开日期选择器对话框并选择任何日期时,日期会显示在输入文本框中,但我想在输入文本框中发生任何更改时调用函数 .

现在,如果我在输入文本框中手动输入任何值,我使用(输入)指令触发函数,它正常工作,如代码所示 . 我希望在使用日期选择器对话框更改日期时触发相同的功能 .

2. 从日期选择器对话框中选择时,我还想将日期格式从 mm/dd/yyyy 更改为 dd/mm/yyyy . 这里,mm / dd / yyyy在此指令中默认设置 .

<input matInput [matDatepicker]="organizationValue" formControlName="organizationValue" (input)="orgValueChange(i)">
<mat-datepicker-toggle matSuffix [for]="organizationValue"></mat-datepicker-toggle>                 
<mat-datepicker #organizationValue></mat-datepicker>

2 回答

  • 6

    docs您可以根据您的要求使用以下事件之一

    @Output()
    dateChange(): EventEmitter<MatDatepickerInputEvent<D>>
    

    在触发更改事件时发出 .

    @Output()
    dateInput(): EventEmitter<MatDatepickerInputEvent<D>>
    

    在此事件上触发输入事件时发出 .

    例如:

    <input matInput #ref [matDatepicker]="organizationValue" formControlName="organizationValue" (dateChange)="orgValueChange(ref.value)">
    

    要么

    <input matInput #ref [matDatepicker]="organizationValue" formControlName="organizationValue" (dateInput)="orgValueChange(ref.value)">
    
  • 8
    • 在您的html中,您可以使用(ngModelChange)=“functionName()”来触发任何更改日期的函数,并在您的ts中声明该函数 .

    • 要更改日期的格式:

    将其添加到 app.module.ts

    import{MatDateFormats, MAT_DATE_FORMATS, NativeDateAdapter, DateAdapter} from '@angular/material';
    
    const MY_DATE_FORMATS = {
        parse: {
            dateInput: { day: 'numeric', month: 'numeric', year: 'numeric' }
        },
        display: {
            dateInput: 'input',
            monthYearLabel: { year: 'numeric', month: 'short' },
            dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
            monthYearA11yLabel: { year: 'numeric', month: 'long' },
        }
     };
    
    export class AppDateAdapter extends NativeDateAdapter {
    
        format(date: Date, displayFormat: Object): string {
            if (displayFormat === 'input') {
                const day = date.getDate();
                const month = date.getMonth() + 1;
                const year = date.getFullYear();
                return `${day}/${month}/${year}`;
            } else {
                return date.toDateString();
            }
        }
    }
    

    app.module.ts 的提供者中添加以下内容:

    {provide: DateAdapter, useClass: AppDateAdapter},  
    {provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS}
    

相关问题