Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 Date format MM/dd/yyyy in reactive form

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.

like image 918
user1041169 Avatar asked Jul 29 '18 20:07

user1041169


2 Answers

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">
like image 116
Fernando Raposo Avatar answered Sep 18 '22 14:09

Fernando Raposo


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

like image 26
SiliconSoul Avatar answered Sep 16 '22 14:09

SiliconSoul