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

Full Calendar在ngx-bootstrap标签中加载时主体不显示的问题

问题:ngx-bootstrap标签中FullCalendar初始仅显示表头,点击后才加载完整日历

我在ngx-bootstrap的标签组件里集成FullCalendar时遇到了个麻烦——页面初始加载后,日历只显示表头部分,必须点击表头的按钮(比如切换月份)才能渲染出完整的日历视图。我已经把相关的初始化逻辑移到ngOnInit里了,但问题还是没解决。

组件代码

import {AfterViewInit, Component, OnInit} from '@angular/core';
import dayGridPlugin from "@fullcalendar/daygrid";

@Component({
  selector: 'app-calendar-module',
  templateUrl: './calendar-module.component.html',
  styleUrls: ['./calendar-module.component.scss']
})
export class CalendarModuleComponent implements OnInit, AfterViewInit {
  public calendarPlugins = [dayGridPlugin];
  
  constructor() { }

  ngOnInit() { }
  ngAfterViewInit(){ }
}

模板代码

<full-calendar 
  defaultView="dayGridMonth" 
  [plugins]="calendarPlugins" 
  [weekends]="false" 
  [events]="[
    { title: 'event 1', start:'2019-08-19', end:'2019-08-30', color:'red' }
  ]"
></full-calendar>

解决方案尝试

我之前在项目里也碰到过几乎一模一样的问题,根源其实是ngx-bootstrap的标签在初始状态下,非激活标签的DOM元素是被隐藏的(或者说处于未完全渲染的状态),FullCalendar没法正确计算容器的尺寸,所以就只渲染了表头。给你几个亲测有效的解决思路:

1. 手动触发日历渲染(最常用的解决办法)

通过ViewChild拿到FullCalendar的实例,在标签被激活的时候手动调用渲染方法,强制日历重新计算尺寸并渲染。

修改你的组件代码:

import {AfterViewInit, Component, OnInit, ViewChild, ChangeDetectorRef} from '@angular/core';
import dayGridPlugin from "@fullcalendar/daygrid";
import { FullCalendarComponent } from '@fullcalendar/angular'; // 别忘导入这个组件

@Component({
  selector: 'app-calendar-module',
  templateUrl: './calendar-module.component.html',
  styleUrls: ['./calendar-module.component.scss']
})
export class CalendarModuleComponent implements OnInit, AfterViewInit {
  public calendarPlugins = [dayGridPlugin];
  @ViewChild(FullCalendarComponent) calendarComponent!: FullCalendarComponent;

  constructor(private cdr: ChangeDetectorRef) { }

  ngOnInit() { }
  
  ngAfterViewInit(){
    // 如果日历所在的标签是默认激活的,加个小延迟确保DOM已就绪
    setTimeout(() => {
      this.calendarComponent.getApi().render();
      this.cdr.detectChanges(); // 通知Angular更新视图
    }, 100);
  }

  // 把这个方法绑定到父组件的标签切换事件上
  onTabActivated() {
    this.calendarComponent.getApi().render();
    this.cdr.detectChanges();
  }
}

然后在父组件的标签模板里绑定激活事件(假设用的是ngx-bootstrap的tabset):

<tabset (tabChange)="calendarModule.onTabActivated()">
  <tab heading="日历">
    <app-calendar-module #calendarModule></app-calendar-module>
  </tab>
</tabset>

2. 给日历容器设置明确的高度

有时候日历容器没有固定高度,也会导致初始渲染异常。在组件的样式文件里加这段:

:host ::ng-deep .fc {
  height: 600px;
  min-height: 600px;
}

这样强制给日历容器一个固定高度,FullCalendar就能正确渲染了。

3. 换个生命周期钩子试试

如果上面的方法还不行,试试把渲染逻辑移到ngAfterContentInit里,这个钩子会在组件内容完全初始化后触发:

ngAfterContentInit() {
  setTimeout(() => {
    this.calendarComponent?.getApi().render();
  }, 50);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:01:54