Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two datepickers on angular material with different date format

I'm trying to get two datepickers on Angular with different date format, the issue is that the only way that is possible to change the format is with a DataAdapter that's customize, but that applies to all the datepickers.

Any idea?

Thanks!

like image 440
Nestor Avatar asked Jan 28 '23 00:01

Nestor


2 Answers

I know this is quite old and since Angular 6+, you can't mix ngModel and reactiveforms anymore. Here's a little workaroud with a little css tweak so the datepicker popup still shows up in the right place.

datepicker.component.html

<input #dateInput class="hidden-date-input" [matDatepicker]="datepicker" formControlName="myDatePicker" readonly>
<input placeholder="Choose a date" class="form-control" (click)="datepicker.open()" [readonly]="true" [value]="fullDate">
<mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
<mat-datepicker #datepicker disabled="false" (closed)="dateInput.blur()"></mat-datepicker>

datepicker.component.ts

...
export class DatepickerComponent {
get fullDate() {
    const dateValue = this.form.controls['myDatePicker'].value;
    if (!dateValue) { return ''; }
    return moment(dateValue).format('MM/DD/YYYY');
  }

css

.hidden-date-input {
  width: 0;
  border: none;
  padding: 0;
}

Thank you PraSame for the idea.

like image 39
bokswagen Avatar answered Feb 05 '23 17:02

bokswagen


You can add an extra input field for showing the date picker. And setting the original datepicker as hidden.

This will let you set the one way binding for the bounded property and let you apply a pipe of 'date' type. Within that pipe, you can have any format of your choice.

<mat-form-field>
    <input matInput [matDatepicker]="picker" [(ngModel)]="myDate" placeholder="Date" hidden=true [readonly]="true">
    <input matInput [ngModel]="myDate | date : 'dd/MM/y'" [ngModelOptions]="{standalone: true}" placeholder="Date" (click)="picker.open()" [readonly]="true">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker name="myDate" ngDefaultControl></mat-datepicker>
</mat-form-field>
like image 95
Prachi Avatar answered Feb 05 '23 17:02

Prachi