Angular 4中input date类型日期改为dd/MM/yy格式的实现方法问询
解决Angular中Input Date自定义显示格式为dd/MM/yy的问题
首先得明确一个关键点:原生的<input type="date">控件的显示格式是由用户的浏览器/系统区域设置决定的,没法直接通过HTML属性修改它的默认显示样式。所以要实现你想要的dd/MM/yy格式,得借助Angular的特性来处理,下面给你两种可行的方案:
方案一:利用Getter/Setter结合DatePipe实现
这种方式适合单个组件内的简单场景,不用额外写指令,直接在组件里处理格式转换:
步骤1:导入并注入DatePipe
在你的组件.ts文件里,先导入Angular的DatePipe,然后在构造函数里注入它:
import { Component } from '@angular/core'; import { DatePipe } from '@angular/common'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', providers: [DatePipe] // 把DatePipe添加到组件的提供者中 }) export class YourComponent { books = { published: new Date() }; // 假设你的books对象结构 constructor(private datePipe: DatePipe) {} // 定义用于双向绑定的属性,处理显示格式 get formattedPublishedDate(): string { // 把Date对象转成dd/MM/yy格式的字符串 return this.datePipe.transform(this.books.published, 'dd/MM/yy') || ''; } set formattedPublishedDate(value: string) { // 把用户输入的dd/MM/yy字符串转成Date对象,赋值给books.published const dateParts = value.split('/'); if (dateParts.length === 3) { const day = parseInt(dateParts[0], 10); const month = parseInt(dateParts[1], 10) - 1; // 注意:Date对象的月份是从0开始的 const year = 2000 + parseInt(dateParts[2], 10); // 把两位年份转成四位(比如18→2018) this.books.published = new Date(year, month, day); } } }
步骤2:修改模板中的Input绑定
把原来的type="date"改成type="text"(因为原生date类型不支持自定义格式),然后绑定到我们定义的formattedPublishedDate属性:
<input type="text" class="form-control" name="published" #published [(ngModel)]="formattedPublishedDate" [ngModelOptions]="{ standalone: true }"/>
这样用户看到的是dd/MM/yy格式的日期,输入后会自动转成Date对象存到books.published里。
方案二:自定义指令实现可复用的日期格式化
如果你的项目里多个地方都需要这种日期格式,写个自定义指令会更方便,代码可以复用:
步骤1:创建自定义指令
新建一个date-formatter.directive.ts文件,内容如下:
import { Directive, ElementRef, HostListener, OnInit } from '@angular/core'; import { DatePipe } from '@angular/common'; @Directive({ selector: '[appDateFormatter]' // 指令的选择器,模板里用这个属性来绑定 }) export class DateFormatterDirective implements OnInit { constructor(private el: ElementRef, private datePipe: DatePipe) {} ngOnInit() { // 组件初始化时,把现有Date对象转成dd/MM/yy格式显示 const initialDate = this.el.nativeElement.value; if (initialDate) { this.el.nativeElement.value = this.datePipe.transform(new Date(initialDate), 'dd/MM/yy') || ''; } } @HostListener('blur') onBlur() { // 失去焦点时,解析用户输入的dd/MM/yy字符串,转成ISO格式(让ngModel能识别) const inputValue = this.el.nativeElement.value; const dateParts = inputValue.split('/'); if (dateParts.length === 3) { const day = parseInt(dateParts[0], 10); const month = parseInt(dateParts[1], 10) - 1; const year = 2000 + parseInt(dateParts[2], 10); const validDate = new Date(year, month, day); // 验证日期是否有效(比如避免31/04/18这种无效日期) if (!isNaN(validDate.getTime())) { this.el.nativeElement.value = this.datePipe.transform(validDate, 'yyyy-MM-dd'); // 触发input事件,通知ngModel更新值 this.el.nativeElement.dispatchEvent(new Event('input')); } } } @HostListener('focus') onFocus() { // 获取焦点时,重新显示成dd/MM/yy格式 const currentValue = this.el.nativeElement.value; if (currentValue) { this.el.nativeElement.value = this.datePipe.transform(new Date(currentValue), 'dd/MM/yy') || ''; } } }
步骤2:在模块中声明指令
在你的组件所在的模块.ts文件里,导入并声明这个指令:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DateFormatterDirective } from './date-formatter.directive'; import { YourComponent } from './your-component.component'; @NgModule({ declarations: [YourComponent, DateFormatterDirective], imports: [CommonModule] }) export class YourModule {}
步骤3:在模板中使用指令
把input改成type="text",然后加上指令属性:
<input type="text" class="form-control" name="published" #published [(ngModel)]="books.published" [ngModelOptions]="{ standalone: true }" appDateFormatter/>
额外提示
- 如果你需要验证用户输入的日期是否有效,可以在setter或者指令的
onBlur方法里添加更多逻辑,比如判断日期的合理性。 - 如果不想自己写代码,也可以考虑用Angular生态里的第三方日期组件(比如Angular Material Datepicker、ngx-bootstrap Datepicker),这些组件都支持自定义显示格式,配置起来更简单。
内容的提问来源于stack exchange,提问作者Pushparaj
相关产品推荐
相关产品推荐

