Reputation: 23
How can I bring the date correctly to the formControl
?
When trying to set the date via setValue
, it does not appear in the same format anymore.
I want the date to appear in the DD-MM-YYYY
format, the same as I bring it in, but when doing the return via code, the component only accepts MM-DD-YYYY
.
I have already tried to invert the DD with MM via code and return, but still nothing done.
HTML
<input matInput [matDatepicker]="picker4" placeholder="Data prevista pagamento" formControlName="dataPrevistaPagto">
<mat-datepicker-toggle matSuffix [for]="picker4"></mat-datepicker-toggle>
<mat-datepicker #picker4></mat-datepicker>
I bring in the date like this:
TS
ModelEdit.dataPrevistaPagto = this.setDate(this.form.get('dataPrevistaPagto').value);
setDate(dataString: string){
var today = new Date(dataString);
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
var dataa = dd + '/' + mm + '/' + yyyy;
return dataa;
}
And I set the date like this:
this.form.get('dataPrevistaPagto').setValue( moment(new Date(this.setDateInverse(this.ModelEdit.dataPrevistaPagto))));
Upvotes: 2
Views: 2892
Reputation: 8269
You can try implementing it using Angular Date Pipe
Have had an existing Stackblitz Demo for your reference.
Just change the current format from Stackblitz yyyy-MM-dd
to your desired format dd-MM-yyyy
or other similar as per on Angular Date Pipe Documentation
@Component({
...,
providers: [ DatePipe ] // Import DatePipe from "@angular/core"
})
export class AppComponent implements OnInit {
currentDate: any = new Date();
constructor(private datePipe: DatePipe) {}
ngOnInit(): void {
// You can use whatever format you like
// see https://angular.io/api/common/DatePipe#pre-defined-format-options
this.currentDate = this.datePipe.transform(this.currentDate, 'dd-MM-yyyy');
}
}
Upvotes: 2