Change format of md-datepicker in Angular Material with momentjs

前端 未结 13 802
再見小時候
再見小時候 2020-11-28 09:01

Angular material introduced a new date picker component found here.

I want the date returned by this component to be in the format yyy-mm-dd but I am not su

13条回答
  •  暖寄归人
    2020-11-28 09:44

    I'd like to provide my solution that's 100% based off of Christiaan Westerbeek's post. I really like what he did, but I personally wanted something a bit more simplistic.

    appConfig.js

    // config params in global scope that need to be set outside of Angular (due to Angular limitiations)
    var appConfig = {
        // enables the dynamic setting of md-datepicker display masks (eg. when user changes language from English to Spanish)
        date: {
            // default mask
            format: "MM/dd/yyyy",
    
            // md-datepicker display format
            mdFormatDate: function (date) {
                if (date && date instanceof Date) {
                    return date.format(appConfig.date.format);
    
                } else {
                    return null;
    
                }
    
            }
    
        }
    
    };
    

    app.material.config.js

    // set angular material config
    app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
        // this is a global object set inside appConfig.js
        $mdDateLocaleProvider.formatDate = appConfig.date.mdFormatDate;
    
    }]);
    

    some service file that deals with localization/translations/etc

    // inside the service where you'd track the language/locale change
    service._updateConfigDateFormat = function (theNewDateFormat) {
        // where theNewDateFormat is something like 'yyyy/MM/dd' or whatever
        daepConfig.date.format = theNewDateFormat;
    
    };
    

    It should be noted that this solution will not live re-format your md-datepicker's display values. It will only work when the model changes values.

提交回复
热议问题