You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中FullCalendar事件数组更新后无需刷新显示新事件的方法

解决Angular中FullCalendar新增事件无需刷新页面显示的问题

你的核心问题是:新增事件时仅向eventsJson数组push元素,但FullCalendar无法感知到数组内容变化——因为数组是引用类型,push操作不会改变原数组的内存地址,Angular变更检测和FullCalendar都不会触发重新渲染。下面是两种直接有效的解决方法:


方法1:通过更新数组引用触发FullCalendar更新

在新增事件的回调中,push新元素后,创建新数组并重新赋值给calendarOptions.events,利用引用变化触发组件更新:

修改createEvent方法:

createEvent(){
  this.eventService.create(this.newEvent).subscribe({
    next: (response) => {
      // 添加新事件到本地数组
      this.eventsJson.push({title: this.newEvent.name, start:this.newEvent.startTime});
      // 关键:创建新数组,更新calendarOptions的events属性
      this.calendarOptions.events = [...this.eventsJson];
      
      this.newEvent = new EventDto();
      this.close();
    },
    error: (error) => {
      Swal.fire({
        icon: 'error',
        title: 'Oops...',
        text: error.error[Object.keys(error.error)[0]],
      });
    }
  })
}

原理:FullCalendar会监听calendarOptions.events的引用变化,当你用扩展运算符[...this.eventsJson]创建新数组时,引用地址改变,FullCalendar会自动重新渲染事件列表。


方法2:直接调用FullCalendar API强制刷新

通过ViewChild获取Calendar实例,调用官方API的refetchEvents方法手动刷新:

步骤1:添加ViewChild引用

在组件顶部导入并定义ViewChild:

import { FullCalendarComponent } from '@fullcalendar/angular';

// ...

export class CalendarComponent implements OnInit{
  // 引用模板中的full-calendar组件
  @ViewChild('mycal') calendarComponent!: FullCalendarComponent;
  
  // 其余代码不变
}

步骤2:在新增事件后调用刷新API

修改createEvent方法:

createEvent(){
  this.eventService.create(this.newEvent).subscribe({
    next: (response) => {
      this.eventsJson.push({title: this.newEvent.name, start:this.newEvent.startTime});
      // 调用FullCalendar API强制刷新事件
      this.calendarComponent.getApi().refetchEvents();
      
      this.newEvent = new EventDto();
      this.close();
    },
    error: (error) => {
      Swal.fire({
        icon: 'error',
        title: 'Oops...',
        text: error.error[Object.keys(error.error)[0]],
      });
    }
  })
}

原理:直接通过FullCalendar的底层API触发事件重新获取和渲染,适合需要手动控制刷新时机的场景。


可选优化:初始化逻辑整理

为避免多次调用getAllEvents导致重复事件,建议初始化时直接替换数组而非push:

getAllEvents(){
  this.eventService.getAllByCompany().subscribe({
    next: (response) => {
      this.events = response;
      // 直接映射为新数组,替代循环push
      this.eventsJson = response.map(event => ({
        title: event.name,
        start: event.startTime
      }));
      this.calendarOptions.events = this.eventsJson;
    },
    error: (error) => {
      this.events = [];
      this.eventsJson = [];
      this.calendarOptions.events = [];
    }
  })
}

内容的提问来源于stack exchange,提问作者Csaba Simon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 03:45:14