import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
Inject,
OnDestroy
} from '@angular/core';
import {MatCalendar} from '@angular/material/datepicker';
import {DateAdapter, MAT_DATE_FORMATS, MatDateFormats} from '@angular/material/core';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
/** @title Datepicker with custom calendar header */
@Component({
selector: 'datepicker-custom-header-example',
templateUrl: 'datepicker-custom-header-example.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DatepickerCustomHeaderExample {
exampleHeader = ExampleHeader;
}
/** Custom header component for datepicker. */
@Component({
selector: 'example-header',
styles: [`
.example-header {
display: flex;
align-items: center;
padding: 0.5em;
}
.example-header-label {
flex: 1;
height: 1em;
font-weight: 500;
text-align: center;
}
.example-double-arrow .mat-icon {
margin: -22%;
}
`],
template: `
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ExampleHeader implements OnDestroy {
private _destroyed = new Subject();
constructor(
private _calendar: MatCalendar, private _dateAdapter: DateAdapter,
@Inject(MAT_DATE_FORMATS) private _dateFormats: MatDateFormats, cdr: ChangeDetectorRef) {
_calendar.stateChanges
.pipe(takeUntil(this._destroyed))
.subscribe(() => cdr.markForCheck());
}
ngOnDestroy() {
this._destroyed.next();
this._destroyed.complete();
}
get periodLabel() {
return this._dateAdapter
.format(this._calendar.activeDate, this._dateFormats.display.monthYearLabel)
.toLocaleUpperCase();
}
previousClicked(mode: 'month' | 'year') {
this._calendar.activeDate = mode === 'month' ?
this._dateAdapter.addCalendarMonths(this._calendar.activeDate, -1) :
this._dateAdapter.addCalendarYears(this._calendar.activeDate, -1);
}
nextClicked(mode: 'month' | 'year') {
this._calendar.activeDate = mode === 'month' ?
this._dateAdapter.addCalendarMonths(this._calendar.activeDate, 1) :
this._dateAdapter.addCalendarYears(this._calendar.activeDate, 1);
}
}