Angular Material mat-datepicker (change) event and format

后端 未结 5 2114
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 20:42

I am using angular material datepicker directive and I have few problems.

1. When I open date picker dialog and select any date, date shows up in i

5条回答
  •  伪装坚强ぢ
    2020-12-18 21:32

    1. In your html you can use (ngModelChange)="functionName()" to trigger any function with the change of the date and declare the function in your ts.

    2. To change the format of the date :

    Add this to 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();
            }
        }
    }
    

    Add the below in providers of app.module.ts:

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

提交回复
热议问题