如何改变Angular FullCalendar事件的颜色(特定事件)?

问题描述 投票:-2回答:1

我正在使用PrimeNG Full Calendar组件制作一个Angular应用程序,这个应用程序。https:/primefaces.orgprimengshowcase#fullcalendar。

那是基于Angular FullCalendar组件,这个。https:/fullcalendar.io

在这里你可以找到我的全部代码。https:/bitbucket.orgdgs_poste_teamsoc_calendarsrcmaster。

我发现在我的日历上,要想改变事件的背景颜色有一些困难,我必须根据不同的事件信息(例如:如果事件在07:00开始是绿色的,如果在15:00开始是红色的,如果在23:00开始是红色的),有不同的事件背景颜色。我必须根据不同的事件信息(例如,事件的开始时间:如果一个事件在07:00开始是绿色的,如果它在15:00开始是红色的,如果它在23:00开始是蓝色的,但这个逻辑在这个时候并不重要)有不同的事件背景颜色。

在我的项目中,我把外部事件拖到我的日历中,就像这样。https:/fullcalendar.iodocsexternal-dragging-demo。

所以,我想要的是,当我把一个事件拖到我的日历中时,它的背景将根据开始时间有一个特定的颜色。

所以,正如你所看到的,在我的BitBucket仓库中,我有这样的内容 FullcalendarComponent 处理包含从外部组件接收事件的日历的组件。

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { EventService } from '../event.service';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import listPlugin from '@fullcalendar/list';
import interactionPlugin, { Draggable } from '@fullcalendar/interaction';
import { FullCalendar } from 'primeng';

@Component({
  selector: 'app-fullcalendar',
  templateUrl: './fullcalendar.component.html',
  styleUrls: ['./fullcalendar.component.css']
})
export class FullcalendarComponent implements OnInit {

  events: any[];
  options: any;
  header: any;

  //people: any[];

  @ViewChild('fullcalendar') fullcalendar: FullCalendar;


  constructor(private eventService: EventService) {}

  ngOnInit() {
    this.eventService.getEvents().then(events => { this.events = events;});

    this.options = {
        plugins:[ dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin ],
        defaultDate: '2017-02-01',
        header: {
            left: 'prev,next',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        editable: true,
        nextDayThreshold: '06:00:00',
        //eventColor: '#378006',

        dateClick: (dateClickEvent) =>  {         // <-- add the callback here as one of the properties of `options`
          console.log("DATE CLICKED !!!");
        },

        eventClick: (eventClickEvent) => {
          console.log("EVENT CLICKED !!!");
        },

        eventDragStop: (eventDragStopEvent) => {
          console.log("EVENT DRAG STOP !!!");
        },

        eventReceive: (eventReceiveEvent) => {
          console.log(eventReceiveEvent);
          eventReceiveEvent.event.setAllDay(false, {maintainDuration: true});
          eventReceiveEvent.eventColor = '#378006';
          eventReceiveEvent.event.eventColor = '#378006';
          eventReceiveEvent.event.css('background-color', '#378006');
          this.eventService.addEvent(eventReceiveEvent);
        }
    };

  }

}

我发现,添加这个选项 eventColor: '#378006', 我可以改变默认的事件背景颜色......但这种方式是静态的,我不能处理不同类型的事件的不同颜色(我只是简单地改变所有事件的默认颜色,所以这对我的用例来说不是很好)。

我有这个方法,用来修改拖入日历的事件。

eventReceive: (eventReceiveEvent) => {
  console.log(eventReceiveEvent);
  eventReceiveEvent.event.setAllDay(false, {maintainDuration: true});
  eventReceiveEvent.eventColor = '#378006';
  eventReceiveEvent.event.eventColor = '#378006';
  eventReceiveEvent.event.css('background-color', '#378006');
  this.eventService.addEvent(eventReceiveEvent);
}

我在想,这可能是一个很好的候选地方来放置这个行为...正如你在我的代码中看到的,我试图使用一些方法来设置事件的颜色,但它没有工作...当我的页面被渲染时,我仍然获得默认的事件颜色。

为什么会这样?有什么问题吗?我遗漏了什么?我怎样才能通过代码获得想要的行为并设置事件颜色?

javascript angular fullcalendar primeng primeng-calendar
1个回答
3
投票

每个事件都支持一个属性backgroundColor来决定你的事件的背景颜色。

查看这里:- https:/fullcalendar.iodocsevent-object。

为了使这个颜色的决定在事件被添加时自动进行,我把你的服务中的promise改为observable。每当你通过你的addevent服务方法推送新的事件时,你的组件的ngoninit订阅将收到更新的数据并应用背景颜色。这也将防止你的原始数据改变,因为只有你的组件需要这个颜色来显示。而不是您的原始数据。

服务变更:-

  1. public eventData = new BehaviorSubject(this.events);
  2. getEvents(): Observable<any[]> {
      return this.eventData.asObservable();
     }
  3. addEvent(event) {
      //this.events.push(event);
      //console.log("EVENT:")
      //console.log(event.event.title);
      console.log(event.event.start);
      console.log(event);
      const newEvent = {id: 5, title: event.event.title, start: event.event.start, end: event.event.end};
      this.events.push(newEvent);
      this.eventData.next([...this.events]);
     }

更改后的完整服务:-

import { Injectable } from '@angular/core';
//import { Http } from '@angular/http';
import { HttpClientModule, HttpClient } from '@angular/common/http'
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class EventService {

  private events = [
    {id: 1, title: 'All Day Event', start: '2017-02-01'},
    {id: 2, title: 'Long Event', start: '2017-02-07', end: '2017-02-10T7:00:00'},
    {id: 3, title: 'Repeating Event', start: '2017-02-09T16:00:00'},
    {id: 3, title: 'test', start: '2017-02-20T07:00:00'},
  ];

  private people = [
    {id: 1, name: "PERSONA 1"},
    {id: 2, name: "PERSONA 2"},
    {id: 3, name: "PERSONA 3"},
    {id: 4, name: "PERSONA 4"},
    {id: 5, name: "PERSONA 5"},
  ]

  public eventData = new BehaviorSubject(this.events);


  constructor(private http: HttpClient) {}

  /*
  getEvents(): Promise<any[]> {
    return this.http.get('assets/json_mock/calendarevents.json')
      .toPromise()
      .then(res => JSON.parse(JSON.stringify(res)).data)
      .then(res => {
        console.log(res);
        // you returned no value here!
        return res;
      })
  }
  */

getEvents(): Observable<any[]> {
  return this.eventData.asObservable();
}

addEvent(event) {
  //this.events.push(event);
  //console.log("EVENT:")
  //console.log(event.event.title);
  console.log(event.event.start);
  console.log(event);
  const newEvent = {id: 5, title: event.event.title, start: event.event.start, end: event.event.end};
  this.events.push(newEvent);
  this.eventData.next([...this.events]);
}

getPeople(): Promise<any[]> {
  return Promise.all(this.people)
      .then(res => {
        console.log(res);
        return res;
      })
}

}

在你的fullcalendar.component.ts中,你可以在从服务中接收事件的地方改变观察到的颜色,比如:-。

this.eventService.getEvents().subscribe(events => { this.events = events.map((event) => {
  var date = new Date(event.start);
  var hour = date.getHours();
  event['backgroundColor'] = hour === 5? 'red': (hour === 7 ? 'green' : 'black');
  return event;
})});

输出:-

enter image description here

修改后的完整的fullcalendar.component.ts:-。

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { EventService } from '../event.service';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import listPlugin from '@fullcalendar/list';
import interactionPlugin, { Draggable } from '@fullcalendar/interaction';
import { FullCalendar } from 'primeng';

@Component({
  selector: 'app-fullcalendar',
  templateUrl: './fullcalendar.component.html',
  styleUrls: ['./fullcalendar.component.css']
})
export class FullcalendarComponent implements OnInit {
  //backgroundColor
  events: any[];
  options: any;
  header: any;

  //people: any[];

  @ViewChild('fullcalendar') fullcalendar: FullCalendar;


  constructor(private eventService: EventService) {}

  ngOnInit() {
    this.eventService.getEvents().subscribe(events => { this.events = events.map((event) => {
      var date = new Date(event.start);
      var hour = date.getHours();
      event['backgroundColor'] = hour === 5? 'red': (hour === 7 ? 'green' : 'black');
      return event;
    })});

    this.options = {
        plugins:[ dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin ],
        defaultDate: '2017-02-01',
        header: {
            left: 'prev,next',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        editable: true,
        nextDayThreshold: '06:00:00',

        dateClick: (dateClickEvent) =>  {         // <-- add the callback here as one of the properties of `options`
          console.log("DATE CLICKED !!!");
        },

        eventClick: (eventClickEvent) => {
          console.log("EVENT CLICKED !!!");
        },

        eventDragStop: (eventDragStopEvent) => {
          console.log("EVENT DRAG STOP !!!");
        },

        eventReceive: (eventReceiveEvent) => {
          console.log(eventReceiveEvent);
          eventReceiveEvent.event.setAllDay(false, {maintainDuration: true});
          this.eventService.addEvent(eventReceiveEvent);
        }
    };

  }

}

我把服务中的事件时间修改成了如下图所示的输出。

private events = [
    {id: 1, title: 'All Day Event', start: '2017-02-01'},
    {id: 2, title: 'Long Event', start: '2017-02-07', end: '2017-02-10T7:00:00'},
    {id: 3, title: 'Repeating Event', start: '2017-02-09T16:00:00'},
    {id: 3, title: 'test', start: '2017-02-20T07:00:00'},
  ];
© www.soinside.com 2019 - 2024. All rights reserved.