Angular 如何为输入字段设置双向格式化程序?
我喜欢将日期双向绑定到输入控件Angular 如何为输入字段设置双向格式化程序?,angular,typescript,Angular,Typescript,我喜欢将日期双向绑定到输入控件 public dtm : Date; ... this.dtm = new Date (); ... <input type="text" placeholder="DD.MM.YYYY" [(ngModel)]="dtm"/> 公共dtm:日期; ... this.dtm=新日期(); ... 如果我这样做,那么输入将以标准格式显示日期 e、 g.2019年10月19日星期六11:53:00 GMT+0200(CEST) 是否可以为特殊格式(
public dtm : Date;
...
this.dtm = new Date ();
...
<input type="text" placeholder="DD.MM.YYYY" [(ngModel)]="dtm"/>
公共dtm:日期;
...
this.dtm=新日期();
...
如果我这样做,那么输入将以标准格式显示日期
e、 g.2019年10月19日星期六11:53:00 GMT+0200(CEST)
是否可以为特殊格式(例如DD.MM.YYYY)提供一种形式的双向(!)格式化程序
我希望代码中有一个Date实例,但也有一个格式化输出(Date->DD.MM.YYYY)和输入解析(DD.MM.YYYY->Date)
编辑
至少我想要一个双向绑定和一个输出格式化程序。但我不确定如何将[(ngModel)]和日期管道安装到位。在我看来,我们无法直接进行双向绑定。这里有一个解决办法
<input type="date" [ngModel]="dtm | date:'yyyy-MM-dd'" (input)="dtm=$event.target.valueAsDate" />
或
WithparseDate
是一个将字符串解析为日期的函数
如果Angular无法满足您的需要,您可以根据需要定义自定义的日期管道
这里有一个简单的方法。如果我理解正确,那么您可以在TS中根据您的要求设置日期格式:
进口:
import { DatePipe } from "@angular/common"
HTML:
import { DatePipe } from "@angular/common"
<mat-form-field>
<input matInput [matDatepicker]="dp1" [(ngModel)]="dtm" (dateInput)="change($event.target.value, $event)" placeholder="Choose a date">
<mat-datepicker-toggle matSuffix [for]="dp1"></mat-datepicker-toggle>
<mat-datepicker #dp1></mat-datepicker>
</mat-form-field>
import { Component } from "@angular/core";
import { DatePipe } from "@angular/common";
@Component({
selector: "table-filtering-example",
styleUrls: ["table-filtering-example.css"],
templateUrl: "table-filtering-example.html",
providers: [DatePipe] -- Add in Providers array
})
export class TableFilteringExample {
public dtm: Date;
selectedDate: any;
constructor(public datepipe: DatePipe) { --Inject here
this.dtm = new Date();
}
change(date: string, event) {
if (event.value != undefined) {
this.selectedDate = this.datepipe.transform(date, "M/d/yyyy");
console.log(this.selectedDate);
}
}
}