简体   繁体   English

使用 Angular 日期管道格式化 ngModel 中的日期时间

[英]Formatting date time in ngModel in form with Angular date pipe

I have this below where birthDate is "1938-08-08T00:00:00" and I want it to be "dd/MM/yyyy", but I can't seem to figure out how to use the Angular date pipe in ngModel .我在下面有这个,其中birthDate是“1938-08-08T00:00:00”,我希望它是“dd/MM/yyyy”,但我似乎无法弄清楚如何在ngModel使用 Angular 日期管道.

<input type="text" class="form-control" placeholder="ex. MM/DD/YYYY" [(ngModel)]=matterData.birthDate name="birthDate">

I tried this with no luck:我没有运气就试过这个:

[(ngModel)]={{matterData.birthDate | date: 'dd/MM/yyyy'}}

The only way I can get it to work is if I format the date in the .ts code first with Angular 'formatDate()'我可以让它工作的唯一方法是,如果我首先使用 Angular 'formatDate()' 在 .ts 代码中格式化日期

I don't understand why you want to format it inside a ngModel.我不明白你为什么要在 ngModel 中格式化它。

One way data binding (Interpolation {{}})doesn't work inside a two way databinding.一种方式数据绑定(插值{{}})在双向数据绑定中不起作用。 If you want to use pipe, I would instead suggest to use a value attribute instead of ngModal.如果你想使用管道,我会建议使用 value 属性而不是 ngModal。

Your HTML should look like:您的 HTML 应如下所示:

<input type="text" class="form-control" placeholder="ex. MM/DD/YYYY" [value]="matterData.birthDate | date: 'dd/MM/yyyy'" name="birthDate">

Here is a live example for the same.这是一个相同的实例。 https://stackblitz.com/edit/angular-ubpthb https://stackblitz.com/edit/angular-ubpthb

在 Angular 9 上,这对我有用,有两种绑定方式:

<input type="date" class="form-control" name="birthDate" [(ngModel)]="matterData.birthDate" [ngModel]="matterData.birthDate | date:'dd/MM/yyyy'" required>

参考 - 在 ngModel 中在 Angular 的 INPUT 元素上使用管道

<input type="text" class="form-control" placeholder="ex. MM/DD/YYYY" [ngModel]="matterData.birthDate | date: 'dd/MM/yyyy'" (ngModelChange)="matterData.birthDate=$event" name="birthDate">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM