问题
I need help in customizing the angular material date picker i.e,https://material.angular.io/components/datepicker/overview. The calendar should not close once we click on the date. I should be able to have 2 buttons, one is 'cancel' and another is 'save'. Once the save button is clicked, the calendar should be closed.
回答1:
I don't know if it's a better solution, but based on this SO answer, I think that the solution is use a menu with a calendar inside.
As we need an input we need at least two functions, one to parse the value of the input to a Date Object, and another to format the value of the input when we has a Date Object.
As I want this "special" datepicker can format the date in severals ways, YYYY-MM-DD and DD/MM/YYYY I need tree variables
placeHolder:string="DD/MM/YYYY"
separator:string;
order:number[]=[];
A function give us the value of "separator and order"
init(placeholder:string)
{
this.separator=placeholder.replace(/[YMD]/g,'').substr(0,1)
const parts=placeholder.replace(/[.\/]/g,'-').split('-')
this.order[0]=parts.indexOf('YYYY')
this.order[1]=parts.indexOf('MM')
this.order[2]=parts.indexOf('DD')
}
So, our function parse and formats becomes like
format(date:any)
{
if (!date)
return null;
const parts=[''+date.getFullYear(),
("00" + (date.getMonth() + 1)).slice(-2),
("00" + date.getDate()).slice(-2)]
return parts[this.order[0]]+this.separator+
parts[this.order[1]]+this.separator+
parts[this.order[2]]
}
parse(value:string)
{
const parts=value?value.replace(/[.\/]/g,'-').split('-'):[]
const date:any=(parts.length==3)?
new Date(parts[this.order[0]]+'-'+parts[this.order[1]]+'-'+parts[this.order[2]]):
null
return date && date.getTime && date.getTime()?date:null
}
An auxiliar function aloow us in (blur) reformatear the value
tryFormat(value:string)
{
const date=this.parse(value)
this.date=date?this.format(date):value
}
And a function when the "menu" is open, allow change the active date of the calendar that get in a ViewChild
@ViewChild('calendar',{static:false}) calendar:any
onOpen()
{
if (this.date)
{
const date=this.parse(this.date);
if (date)
{
this.calendar.activeDate=date;
}
}
}
Finally, the .html is like
<mat-form-field class="example-full-width">
<mat-label>Date</mat-label>
<input matInput placeholder="{{placeHolder}}" [(ngModel)]="date" (blur)="tryFormat(date)" >
<button matSuffix mat-icon-button [matMenuTriggerFor]="appMenu" (menuOpened)="onOpen()">
<mat-icon>calendar_today</mat-icon>
</button>
</mat-form-field>
<mat-menu #appMenu="matMenu" class="drop-calendar" >
<div (click)="$event.stopPropagation()">
<mat-calendar #calendar
(selectedChange)="date=format($event)"
[selected]="parse(date)">
</mat-calendar>
</div>
</mat-menu>
And the full code is in the stackblitz
来源:https://stackoverflow.com/questions/60202061/is-there-a-way-to-customize-angular-date-picker