Two datepickers on angular material with different date format

时光毁灭记忆、已成空白 提交于 2020-03-23 18:11:50

问题


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!


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/50616721/two-datepickers-on-angular-material-with-different-date-format

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