Angular Date Pipe Not Working Correctly in Textbox

大憨熊 提交于 2020-12-26 10:40:36

问题


My Date Pipe is not working in Angular. I only want to show as this format MM/dd/yyyy'. How can it be fixed?

Typescript:

this.testDate = new Date(this.singleUser.createDate);
console.log(this.testDate); 

this.userForm = new FormGroup({
  userName: new FormControl(this.singleUser.userName),
  email: new FormControl(this.singleUser.email),
  createDate: new FormControl(this.singleUser.createDate)
});

Console Log: Wed Jul 22 2020 17:18:24 GMT-0700 (Pacific Daylight Time)

HTML:

<mat-form-field class="row" appearance="outline" floatLabel="always">
    <mat-label>Created Date</mat-label>
    <input matInput [readonly]="true" formControlName="createDate" [value] = "testDate | date: 'MM/dd/yyyy'" >
</mat-form-field>

Date is not showing as MM/dd/yyyy and has additional datetime hours seconds, etc


回答1:


Look, you can't use value and formControlName at the same time. Also it shows your form control value instead of value by value attribute.

You need do add some workaround for that. Like this

<mat-form-field class="row" appearance="outline" floatLabel="always">
    <mat-label>Created Date</mat-label>
    <input matInput [readonly]="true" (change)="funcFromTs($event.target.value)" [value] = "testDate | date: 'MM/dd/yyyy'" >
</mat-form-field>

Ts

funcFromTs(value: string) {
   this.userForm.get('createDate').patchValue(value);
}



回答2:


I read Ashot Aleqsanyan's answer which I think is right on the money, I didn't notice before that you set the value both in the formControl and the input itself, which does seem quite wrong.

you can try with his solution or also try to inject the date pipe directly into your component and use it like this:

import { DatePipe } from '@angular/common';

@Component({
   providers: [DatePipe]   // you need to provide datepipe in providers list for your component
})
class YourComponent implements OnInit {

  constructor(private datePipe: DatePipe) {}

  ngOnInit(){
       // you don't want the testDate field
       // this.testDate = new Date(this.singleUser.createDate);

       const createDate = this.datePipe.transform(this.singleUser.createDate, 'yyyy-MM-dd');
       console.log(createDate); 

       this.userForm = new FormGroup({
         userName: new FormControl(this.singleUser.userName),
         email: new FormControl(this.singleUser.email),
         createDate: new FormControl(createDate)
});
  }
}

(I assumed that you do your initialization in the OnInit, anyway you can move the code around the component as you please of course)

I think this should work nicely :)



来源:https://stackoverflow.com/questions/65414341/angular-date-pipe-not-working-correctly-in-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!