Angular Calendar is a component that allows a user to drag and create events in a calendar and also shows events on the month, week, or day view. In this tutorial, we will learn how to implement Angular Calendar component with the feature to drag and create events.
Before building the demo let’s watch the below video and see what are we going to build.
To install Angular CLI run the below-given command:
Run the following command for creating a new Angular Project:
Install angular-calendar & date-fns through npm:
Import the CSS in global styles of the project i.e. src/styles.css.
Import angular-calendar & date-fns in the app.module.ts file as shown in the following code.
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CalendarModule, DateAdapter } from 'angular-calendar'; import { adapterFactory } from 'angular-calendar/date-adapters/date-fns'; import { DragCompComponent } from './view/drag-comp/drag-comp.component'; @NgModule({ declarations: [AppComponent, DragCompComponent], imports: [ BrowserModule, AppRoutingModule, CalendarModule.forRoot({ provide: DateAdapter, useFactory: adapterFactory, }), ], providers: [], bootstrap: [AppComponent], }) export class AppModule {}
Development. Optimization. Maintenance. Everything at Bacancy!
Get ready to lessen your struggle! Hire Angular developer from Bacancy today and start developing your dream product! We are here for you!
Use the following TypeScript code: Business Logic
import { ChangeDetectorRef } from '@angular/core'; import { ChangeDetectionStrategy, Component, OnInit, ViewEncapsulation, } from '@angular/core'; import { CalendarEvent, CalendarEventTitleFormatter } from 'angular-calendar'; import { WeekViewHourSegment } from 'calendar-utils'; import { addDays, addMinutes, endOfWeek } from 'date-fns'; import { fromEvent } from 'rxjs'; import { finalize, takeUntil } from 'rxjs/operators'; function floorToNearest(amount: number, precision: number) { return Math.floor(amount / precision) * precision; } function ceilToNearest(amount: number, precision: number) { return Math.ceil(amount / precision) * precision; } @Component({ selector: 'app-drag-comp', templateUrl: './drag-comp.component.html', styleUrls: ['./drag-comp.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: CalendarEventTitleFormatter, }, ], encapsulation: ViewEncapsulation.None, }) export class DragCompComponent implements OnInit { viewDate = new Date(); weekStartsOn: 0 = 0; dragToCreateActive = false; events: CalendarEvent[] = []; days: any[] = []; slots: any[] = []; constructor(private cdr: ChangeDetectorRef) {} ngOnInit(): void { this.initDays(); } initDays() { this.days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]; for (let i = 0; i < this.days.length; i++) { let a = { day: this.days[i], time: [] }; this.slots.push(a); } } startDragToCreate( segment: WeekViewHourSegment, mouseDownEvent: MouseEvent, segmentElement: HTMLElement ) { const dragToSelectEvent: CalendarEvent = { id: this.events.length, title: 'New slot', start: segment.date, meta: { tmpEvent: true, }, actions: [ { label: '', onClick: ({ event }: { event: CalendarEvent }): void => { this.events = this.events.filter((iEvent) => iEvent !== event); this.removeSlot(event.id); }, }, ], }; this.events = [...this.events, dragToSelectEvent]; const segmentPosition = segmentElement.getBoundingClientRect(); this.dragToCreateActive = true; const endOfView = endOfWeek(this.viewDate, { weekStartsOn: this.weekStartsOn, }); fromEvent(document, 'mousemove') .pipe( finalize(() => { delete dragToSelectEvent.meta.tmpEvent; this.dragToCreateActive = false; this.refresh(); }), takeUntil(fromEvent(document, 'mouseup')) ) .subscribe((mouseMoveEvent: MouseEvent) => { const minutesDiff = ceilToNearest( mouseMoveEvent.clientY - segmentPosition.top, 30 ); const daysDiff = floorToNearest( mouseMoveEvent.clientX - segmentPosition.left, segmentPosition.width ) / segmentPosition.width; const newEnd = addDays(addMinutes(segment.date, minutesDiff), daysDiff); if (newEnd > segment.date && newEnd < endOfView) { dragToSelectEvent.end = newEnd; } this.refresh(); }); } private refresh() { this.events = [...this.events]; this.cdr.detectChanges(); this.getSlots(); } convertTime(t) { return new Date(t).toTimeString(); } convertDay(d) { return new Date(d).toLocaleString('en-us', { weekday: 'long', }); } getSlots() { this.slots.map((day, i) => { this.slots[i].time = []; this.events.forEach((e) => { if (day.day == this.convertDay(e.start)) { this.slots[i].time.push({ startTime: e.start, endTime: e.end, id: e.id, }); } }); }); } removeSlot(id) { for (let j = 0; j < this.slots.length; j++) { this.slots[j].time = this.slots[j].time.filter((t) => t.id !== id); } } }
Use the following HTML code: User Interface
As we are almost done with the implementation of the Angular Calendar let’s complete the process with the final step, to run the application.
Then, open the following URL in your browser: http://localhost:4200
You can visit the source code and clone the github repository to play around with the code.
So this was all about how to implement Angular Calendar Component in your Angular application. I hope now you can easily create your events and play around with the feature. The Angular Calendar component does provide various useful features we will discuss that surely as well! Want to learn more about Angular? Visit the Angular tutorials page! No doubt, you will love the tutorials that our team has been curated for you! Reach out to us in case you have any suggestions/queries/feedback. We’re always delighted to answer!
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.