Angular TypeScript环境下fullcalendar.io获取当前展示月份的方法求助
报错根因
- 第一种jQuery写法是旧版FullCalendar的API,Angular版本的FullCalendar早已不依赖jQuery,不存在该方法,TS类型校验自然不通过
- 第二种写法混淆了配置对象和组件实例:
calendarOptions是纯配置项,只有组件实例才具备getApi()方法
正确实现步骤
- 首先在组件模板中给full-calendar标签添加模板引用变量
<full-calendar #calendarComponent [options]="calendarOptions" ></full-calendar>
- 在组件类中通过
@ViewChild获取日历组件实例
import { FullCalendarComponent } from '@fullcalendar/angular'; import { ViewChild } from '@angular/core'; // 类内部代码 @ViewChild('calendarComponent') calendarComponent!: FullCalendarComponent;
- 编写获取当前展示月份的方法
getCurrentVisibleMonth(): number { // 加可选链避免组件未渲染时调用报错 const calendarApi = this.calendarComponent?.getApi(); if (!calendarApi) return -1; // 返回值为0-11的整数,对应1-12月,需要转1-12格式直接+1即可 return calendarApi.view.currentStart.getMonth(); }
注意:不要在
ngOnInit生命周期内调用该方法,此时组件还未渲染完成,calendarComponent为未赋值状态,建议在ngAfterViewInit或后续用户交互触发的逻辑中调用。
内容的提问来源于stack exchange,提问作者GolfBravo
相关产品推荐
相关产品推荐

