The eventsource property binding in Ionic 2 calendar does not correctly refresh the view

As a newcomer to the world of Ionic, Angular, and TypeScript, I am currently working on developing a calendar that allows users to set appointments (events) and make edits or deletions to them. To achieve this functionality, I have implemented a modal for editing events, with a delete button included. At the moment, I am storing all added events in an object array within a provider class. This provider class contains functions for adding, editing, deleting events, as well as fetching all existing events. The code snippet below demonstrates how this is structured:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class AppointmentServiceProvider {
  currentId: number;
  events: { id: number, title: string, startTime: string,endTime: string, allDay:boolean }[];

  constructor(public http: HttpClient) {
    this.currentId = 0;
    this.events =[];
  }

  getCurrentId(): number{
    // Implementation details not shown
  }

  addEvent(event: { id: number, title: string, startTime: string, endTime: string, allDay:boolean }){
    // Implementation details not shown
  }

  deleteEvent(eventId:number){
    // Implementation details not shown
  }

  getAllEvents():{ id: number, title: string, startTime: string,endTime: string, allDay:boolean }[]{
    // Implementation details not shown
  }
}

Although the item is successfully removed from the array in the provider upon deletion, my view still displays the deleted event. Below is the HTML code for my page view displaying the calendar:

 <calendar [eventSource]="eventSource"
  [calendarMode]="calendar.mode"
  [currentDate]="calendar.currentDate"
  (onEventSelected)="onEventSelected($event)"
  (onTitleChanged)="onViewTitleChanged($event)"
  (onTimeSelected)="onTimeSelected($event)"
  step="30"
  class="calendar">
</calendar>

The corresponding TypeScript code backing this view is as follows:

export class AppointmentPage {
  // Implementation details not shown
}

editEvent(selectedEvent){
   //Implementation details not shown
 }

delete(){
    //Implementation details not shown
  }
 

Despite these implementations, I am facing issues with the refreshing of the event source after deletion. I am seeking assistance in resolving this issue.

Answer №1

After finally finding the solution, I discovered that the ionic2-calendar on GitHub has an event that allows for forcefully loading events. This is necessary when events are manually changed. In order to refresh the view, I added the following code to reference the calendar in my TS file and called the loadEvents function on it.

import { ViewChild } from '@angular/core';

export class AppointmentPage {
  @ViewChild(CalendarComponent) myCalendar:CalendarComponent;

 editEvent(selectedEvent){
   console.log(selectedEvent);
  let modal = this.modalCtrl.create('EventModalPage', {eventTitle: selectedEvent.title, 
                                                          eventId: selectedEvent.id, 
                                                          eventStartTime:selectedEvent.startTime, 
                                                          eventEndTime: selectedEvent.endTime,
                                                          eventAllDay: selectedEvent.allDay,
                                                          type:1});
  modal.present();
  modal.onDidDismiss(data => {
    console.log("after delete outside data block.");
    this.eventSource = [];
    this.eventSource = this.eventService.getAllEvents();


    this.eventSource = this.eventService.getAllEvents();
    this.myCalendar.loadEvents();   // <== added this after updating eventSource

    if (data) {
      console.log("after delete in the data block. Data:" +data);
      let eventData = data;
      //eventData.id= this.eventService.getCurrentId()+1;
      eventData.id = data.id;
      eventData.title = data.title;
      eventData.allDay = data.allDay;
      eventData.startTime = new Date(data.startTime);
      eventData.endTime = new Date(data.endTime);

      //let events = this.eventSource;
      this.eventService.addEvent(eventData);
      //events.push(eventData);
      this.eventSource = [];
      // this.eventSource = this.eventService.getAllEvents();
      setTimeout(() => {
        this.eventSource = this.eventService.getAllEvents();
      });
    }
  });
 }
}

Implementing this change fixed the problem, allowing deleted events to be removed immediately.

Answer №2

In order to refresh your View, you need to clear the eventSource-Array by setting it to an empty Array.

this.eventSource = [];

After that, update your eventSource with new events.

For example:

this.eventSource = this.updateEvents();

This method has been successful for me

Ionic Version: 5.4.16

Ionic2Calendar Version: 0.6.9

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When Ionic Angular app's IonContent scroll element returns an incorrect scrollTop value after navigation completes, what might be the reason behind this unexpected behavior?

In my quest to scroll the ion-content component to the top upon navigating to the page from certain selected pages, I have implemented a solution using the router's NavigationEnd events. However, I have encountered an issue where the IonContent's ...

Is it possible to specify the data type of form control values when using the Angular Reactive form builder?

Is it possible to use typed reactive forms with Angular form builder? I want to set the TValue on the form control to ensure we have the correct type. For example: public myForm= this.fb.group({ name: ['', [Validators.required, Validators.max ...

Definition of DataTypes in TypeScript

My goal seems simple to me, but I am realizing that my experience with Typescript might not be enough. I want to create a type that can accept the following expressions: const dp: DataPoint = [1, 2]; const dp2: DataPoint = [1, 2, 3]; const dps: DataPoints ...

Struggling to access the 'payload' property of an undefined object? In TypeScript, you can easily bind and access JSON objects using *ngFor directive

I've been attempting to retrieve highscores from the server using node angular and making an http request. Although I successfully obtain the JSON file from the server, I am encountering difficulty accessing the fields for processing in the *ngFor lo ...

Troubleshooting: Dealing with Cross-Origin Resource Sharing (CORS)

I'm facing an issue with my server.js files. One of them is located inside the backend folder, and when I run nodemon server.js on localhost:3000, everything runs smoothly. I start Angular by running ng serve inside the angular folder, and logging int ...

Is there any way to deactivate the saved query in react-admin without having to develop a new component?

The latest version of react-admin, version 4, introduced a new feature that allows saving filters. I'm curious about how to disable this functionality without having to create an additional filter button. https://i.stack.imgur.com/uTrUe.gif ...

The recent update to Bootstrap v5 caused a complete disruption in the CSS of our application

My Angular app was originally on Angular 14 and used Bootstrap with SCSS compiled to node-sass/SASS package. It also utilized ng-bootstrap v11 and Bootstrap v4.3.1 for CSS styles. As part of a general upgrade, I needed to update the Angular version to 15. ...

Can Bun automatically bundle my TypeScript files when I save them in VS Code?

Is it feasible for Bun to bundle my TypeScript upon saving a file in VS Code? The instruction manual suggests running bun run index.ts in the command line and including it in the package.json in this manner. However, I am unsure how to automate this proce ...

Please ensure the subscription has completed before proceeding with the loop

I am currently working on an Angular application that retrieves data from an API and uses one of its parameters from a looped array. The issue I'm facing is that the data is pushed in a random order due to the continuous looping without waiting for th ...

Strategies for handling multiple HTTP requests in Angular using RXJS

Within this demonstration application, we have the following structure: A list of articles (loaded upon page initialization) Each article contains a nested object called detail, which is loaded lazily Clicking on an article item will load its details. H ...

How can I emphasize the React Material UI TextField "Cell" within a React Material UI Table?

Currently, I am working on a project using React Material UI along with TypeScript. In one part of the application, there is a Material UI Table that includes a column of Material TextFields in each row. The goal is to highlight the entire table cell when ...

Tips for arranging Angular Material cards in columns instead of rows

I am currently developing a web application using Angular, and I've encountered an issue while trying to display cards in a vertical layout rather than horizontally. My goal is to have the cards fill up the first column (5-6 cards) before moving on to ...

The art of binding styles and classes in code

What is the advantage of using style binding and class binding in Angular compared to directly using HTML style and traditional class attributes? <img src="link_img" [style.width]="imgWidth"> over <img src="link_img" width="200"> Looking fo ...

The ValidationSchema Type in ObjectSchema Seems to Be Failing

yup 0.30.0 @types/yup 0.29.14 Struggling to create a reusable type definition for a Yup validationSchema with ObjectSchema resulting in an error. Attempting to follow an example from the Yup documentation provided at: https://github.com/jquense/yup#ensur ...

Angular 7 introduces updates to the way lists are ordered

I am facing an issue with my code that calls an API for each object in a list called "titles" and then adds the object to another list named "groupDocs". However, due to the asynchronous nature of the API response, the order of objects in the "groupDocs" l ...

Undefined Perception

Trying to obtain values from an observable, my subscription code within the component looks like this: this.checkoutService.getDisabledDate().subscribe (dates=>{this.formattedDate=dates}, (error:any)=>{console.log(error)}); When logging this.forma ...

Unable to process JSON request in Node.js

I have the following data in Angular that I need to pass to a Node API. The data includes a JSON object that is being sent to the Node API using the POST method. var myData = { "que": { "id": 1, "status": 1, "option": [ ...

Exploring Angular Firebase Database Queries

This is my TypeScript file import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database'; @Component({ selector: 'app-candidate- ...

Angular 2 - Alert: (SystemJS) Stack size limit exceeded(…)

Need some help here: Error: (SystemJS) Maximum call stack size exceeded(…) I have a situation where I am facing an error related to the maximum call stack size being exceeded. It seems to be linked to the import of another module in my component. Let&a ...

Electron Searching for Files in Main Directory

We have developed a web application using Angular 2, but we are facing an issue when trying to run it as an Electron application. After branching out the solution and making changes to package.json to launch Electron on start, we encountered an unexpected ...