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

NativeScript (Angular) 框架下 radCalendar 新增事件后视图不更新问题求助

RadCalendar 新增事件不生效解决方案

根因说明

RadCalendar 的 eventSource 输入属性仅检测数组的引用变化,你直接调用 push 方法属于原地修改数组,数组的内存引用没有发生变化,Angular 变更检测不会触发 RadCalendar 的输入更新,因此日历不会渲染新添加的事件。如果你的组件开启了 ChangeDetectionStrategy.OnPush,这个问题会更明显。


快速修复方案

步骤1:替换数组引用而非原地修改

不要直接调用 this.eventSource.push(event),而是用展开运算符生成新数组替换原有引用,触发变更检测:

saveEvent(inputType) {
  this.selectedCalendarDate.setHours(this.timePicker.hour);
  this.selectedCalendarDate.setMinutes(this.timePicker.minute);
  const event = this.calendarService.createCalendarEvent(this.selectedCalendarDate, this.selectedCalendarDate, 'blue', this.medicineType)
  this.dialogShown = false;
  // 替换为新数组,触发Angular变更检测
  this.eventSource = [...this.eventSource, event];
}

步骤2(可选,强制刷新)

如果替换引用后仍未更新,可手动调用 RadCalendar 的 reload 方法强制刷新视图:
首先在组件中引入模板引用对应的日历实例:

import { RadCalendarComponent } from 'nativescript-ui-calendar/angular';
import { ViewChild } from '@angular/core';

// 组件类内声明
@ViewChild('calendar', { static: false }) calendarComp: RadCalendarComponent;

在修改 eventSource 后调用重载方法:

// 接上面的saveEvent代码
this.eventSource = [...this.eventSource, event];
// 加setTimeout避免时序问题,等变更检测完成后再重载
setTimeout(() => {
  this.calendarComp.nativeElement.reload();
}, 0)

进阶优化方案(推荐)

如果你的事件会在多个组件/服务中修改,可以用 RxJS 流式管理事件列表,避免手动同步数组:
修改CalendarEventsService:

import { Injectable } from '@angular/core';
import { Color } from '@nativescript/core';
import { CalendarEvent } from 'nativescript-ui-calendar';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class CalendarEventsService {
  // 用BehaviorSubject封装事件列表,支持订阅更新
  private eventsSubject = new BehaviorSubject<CalendarEvent[]>([]);

  createCalendarEvent(startDate, endDate, color, type) {
    endDate.setHours(endDate.getHours() + 2)
    const event = new CalendarEvent(type, startDate, endDate, false, color);
    // 每次新增事件都生成新数组推送
    const newEvents = [...this.eventsSubject.value, event];
    this.eventsSubject.next(newEvents);
    return event;
  }

  getCalendarEvents() {
    return this.eventsSubject.asObservable();
  }
}

组件中订阅事件流自动更新:

ngOnInit() {
  this.calendarService.getCalendarEvents().subscribe(events => {
    this.eventSource = events;
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:06:04