Angular 10 FullCalendar调用Rest API绑定日历事件的实现方法
Angular 10 FullCalendar 加载API假期数据实现方案
实现逻辑说明
- FullCalendar的日历事件要求至少包含
title(事件显示名称)和start(事件开始时间)两个必填字段,你需要先把接口返回的自定义结构映射为符合FullCalendar要求的事件格式 - 映射规则:接口返回的
holidayGR.holiday对应事件title,date字段对应事件start,原数据id可作为事件ID方便后续操作
完整修改代码
HTML 部分(无需修改)
<full-calendar #calendar [options]="calendarOptions"></full-calendar>
TS 部分
import { Component, OnInit, ViewChild } from '@angular/core'; import { FullCalendarComponent } from '@fullcalendar/angular'; import { CalendarOptions, EventInput } from '@fullcalendar/core'; import dayGridPlugin from '@fullcalendar/daygrid'; import { VacationService } from './vacation.service'; // 调整为你自己的服务实际路径 export class AppComponent implements OnInit { constructor( private vacationService: VacationService, ) {} ngOnInit(): void { this.loadEvents(); } // 引用模板中的日历组件 @ViewChild('calendar') calendarComponent: FullCalendarComponent; calendarOptions: CalendarOptions = { // 注册月视图所需插件 plugins: [dayGridPlugin], initialView: 'dayGridMonth', headerToolbar: { left: '', center: 'title', }, editable: true, // 初始化事件为空数组,请求完成后再赋值 events: [] }; loadEvents(): void { this.vacationService.getAll().subscribe((data: any[]) => { // 转换接口数据为FullCalendar支持的事件格式 const calendarEvents: EventInput[] = data.map(item => ({ id: item.id?.toString(), title: item.holidayGR?.holiday, start: item.date, // 可自定义扩展属性,比如设置事件背景色 backgroundColor: '#2563eb', borderColor: '#2563eb', // 如果需要标记为全天事件,可开启以下配置 // allDay: true })); // 赋值给日历配置的events属性,日历会自动触发重新渲染 this.calendarOptions.events = calendarEvents; }) } }
注意事项
- Angular10推荐使用
@fullcalendar/angular@5.x版本,避免版本不兼容问题 - 如有时区显示需求,可以在
calendarOptions中配置timeZone属性调整时间显示规则 - 事件的样式、交互逻辑均可在转换数据时通过对应属性自定义配置
内容的提问来源于stack exchange,提问作者David Rod
相关产品推荐
相关产品推荐

