I am using Angular 6 with reactive forms and I am trying to figure out how to format the date value returned from a webapi. The date is displaying as 1973-10-10T00:00:00 and I want to format it to 10/10/1973. Below is the code to retrieve the data and display it. The webapi json dob value is 1973-10-10T00:00:00. The dob value in the model is of type Date.
html
<input formControlName="dob" type="text" [value]="dob | date: 'MM/dd/yyyy'" class="form-control" />
binding form
this.userInfoForm = this.fb.group({
'userId': ['', [Validators.required]],
'dob': ['', [Validators.required]]
});
loading saving
this.as.accountUserInfo(this.activeRoute$.ActiveUserId).subscribe(data => {
this.userInfoModel$ = data as UserInfoModel;
this.userInfoForm.patchValue(this.userInfoModel$);
});
api call
accountUserInfo(userId: number) {
return this.http.post(this.url + "UserInfo", userId)
.pipe(
retry(3),
catchError(this.handleError)
)}
I appreciate any help or guidance as how to transform the date to the MM/dd/yyyy format. Setting the html to date value does make it look ok but I don't want to use the built in browser date displays so I need to convert it to a string.
Thanks in advance.
Had that same problem when using datepicker. The solution was simple: Change the input type to "date"
Before:
<input type="text" class="form-control" placeholder="dd/mm/yyyy"
formControlName="inputNascimento" ngbDatepicker #d="ngbDatepicker">
After:
<input type="date" class="form-control" placeholder="dd/mm/yyyy"
formControlName="inputNascimento" ngbDatepicker #d="ngbDatepicker">
It won't matter what is set with the value binding because you have specified the formControlName which will override any existing value. Seems like you can use the DatePipe to format the date when it is set to the FormGroup: https://stackblitz.com/edit/angular-3tp7yz?file=src%2Fapp%2Fapp.component.ts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With