How to change Angular Material Datepicker format in run-time

前端 未结 3 1854
醉话见心
醉话见心 2021-02-01 10:08

I\'m working on an Angular App with Material Design, and I\'m using Moment.js to parse and format dates.

In one of my p

3条回答
  •  情歌与酒
    2021-02-01 10:34

    Thanks for your idea! Just for clarification. You can use non-singleton service for setting custom formatting of datepicker value. Extending your code:

    import { Injectable } from '@angular/core';
        @Injectable({ providedIn: 'root' })
        export class DateTimeService {
            private _format = 'DD.MM.YYYY';
    
            set format(value: string) {
                this._format = value;
            }
    
            public getFormat(): string {
                return this._format;
            }
    
            public getLocale(): string {
                return 'ru-ru';
            }
        }
    

    If you inject this service like this:

    providers: [
            { provide: MAT_DATE_LOCALE, useValue: 'ru-ru' },
            CustomDateAdapter,
            DateTimeService,
            { provide: DateAdapter, useClass: CustomDateAdapter, deps: [DateTimeService] }
    ]
    

    you can store any value from your component during component working.

    constructor(private dateTimeService: DateTimeService) {
        }
    
        ngOnInit() {
            this.dateTimeService.format = this.format;
        }
    

提交回复
热议问题