我正在尝试使用 Material 日期选择器来允许用户进行预订。当用户在日期选择器中单击下个月或上个月时,我想调用内部方法。我可以看到 nextClicked 和 previousClicked 方法,但这些方法似乎没有发出,所以我无法执行自己的操作。
<input class="date-selected" [matDatepickerFilter]="checkInFilter" [matDatepicker]="checkInDatepicker" [min]="minDate" (focus)="checkInDatepicker.open()" [(ngModel)]="checkInDate">
<mat-datepicker #checkInDatepicker (nextClicked)="nextMonth($event)"
(previousClicked)="previousMonth($event)">
</mat-datepicker>
nextMonth(event) {
console.log(event);
}
previousMonth(event) {
console.log(event);
}
当用户单击日期选择器中的下一个/上一个时,是否可以调用我自己的方法?
最佳答案
我通过实现 customHeader 和共享服务解决了这个问题。
在自定义 header 中,我调用共享服务中的一个方法,该方法设置一个变量并对此进行观察。
然后在主组件中,我订阅构造函数中的可观察对象并调用我的自定义方法。
自定义 header 方法
previousClicked(mode: 'month' | 'year') {
this._calendar.activeDate = mode === 'month' ?
this._dateAdapter.addCalendarMonths(this._calendar.activeDate, -1) :
this._dateAdapter.addCalendarYears(this._calendar.activeDate, -1);
this.calendarService.previousMonthClick(this._dateAdapter.getMonth(this._calendar.activeDate));
}
共享服务
private _previousMonthClick = new Subject();
previousMonthClick$ = this._previousMonthClick.asObservable();
....
previousMonthClick(month) {
this._previousMonthClick.next(month);
}
主要组件
constructor(private calendarService: CalendarService) {
calendarService.previousMonthClick$.subscribe(e => this.previousMonth(e));
}
...
previousMonth(event) {
console.log(event);
}
关于Angular Material Datepicker - nextClicked,previousClicked 不发射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57460014/