如何在 ng-bootstrap 中将默认格式设置为 ('dd/mm/yyyy')

use*_*191 5 html bootstrap-4 angular

https://puu.sh/yThgV/bd55df9829.png

html

<label for="date">{{ "date" | translate }}</label>
<input type="date" class="form-control checking-field" id="date">
Run Code Online (Sandbox Code Playgroud)

我想得到那种格式('dd/mm/yyyy')。有什么建议吗?

Eli*_*seo 5

扩展我的评论

在你的 app.module

import { NgbDatepickerConfig, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';
import { NgbDateFRParserFormatter } from "./ngb-date-fr-parser-formatter"

@Component({
    providers: [{provide: NgbDateParserFormatter, useClass: NgbDateFRParserFormatter}]
})
export class AppComponent {}
Run Code Online (Sandbox Code Playgroud)

在你的 NgbDateFRParserFormater

//your NgbDateFRParserFormater extends from NgbDateParserFormatter
//Is a Injectable that have two functions
@Injectable()
export class NgbDateFRParserFormatter extends NgbDateParserFormatter {
    parse(value: string): NgbDateStruct { //parse receive your string dd/mm/yyy
         //return a NgbDateStruct
         //calculate year,month and day from "value"
        return {year:year,month:month,day:day}
    }

    format(date: NgbDateStruct): string { //receive a NgbDateStruct
        //return a string
        return ''+date.day+'/'+date.month+'/'+date.year;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我根据 https://github.com/ng-bootstrap/ng-bootstrap/issues/2072 中的解决方案将您的可注入实现更改为 momentjs,我尝试了您的解决方案,但有一个错误,其中 NgbDateStruct 值是数字而不是字符串。 (2认同)

小智 -3

一般来说,您需要使用指令。

因此,您可以使用现成的日期时间选择器之一进行角度。像这样:https: //www.npmjs.com/package/angular-date-time-input

或者创建您自己的指令以使其发挥作用。

myModule.directive(
'dateInput',
function(dateFilter) {
    return {
        require: 'ngModel',
        template: '<input type="date"></input>',
        replace: true,
        link: function(scope, elm, attrs, ngModelCtrl) {
            ngModelCtrl.$formatters.unshift(function (modelValue) {
                return dateFilter(modelValue, 'yyyy-MM-dd');
            });

            ngModelCtrl.$parsers.unshift(function(viewValue) {
                return new Date(viewValue);
            });
        },
    };
});
Run Code Online (Sandbox Code Playgroud)

我从以下位置获取了此代码:https ://stackoverflow.com/a/18062552/3710672