How to dynamically update data in an Ionic 2 view using ngFor

In my project called 'Infinite scroll calendar', I am utilizing ngFor to iterate over objects using the 'pipe' mapToIterable.

Unfortunately, I have observed that when I add new properties to an object in the view, the variable is updated but ngFor does not refresh the list. The issue arises when I enter the view initially, everything works fine. However, as I scroll down, data is successfully fetched from the API but the list in ngFor is not updated.

I attempted to solve this problem by encapsulating the code in zone.run() without any success.

#ionic info

Your system information:

Cordova CLI: 6.4.0 
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.1.18
Ionic App Lib Version: 2.1.9
Ionic App Scripts Version: 0.0.45
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v6.5.0
Xcode version: Not installed

Let's delve into some code:

// mapToIterable.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'mapToIterable'})
export class MapToIterablePipe implements PipeTransform {
  transform(value): any {
    let keys = [];
    for (let key in value) {
      keys.push({ key: key, value: value[key]});
    }
    return keys;
  }
}

.

// index.ts
export class Appointments {
  appointments = {};
  current_date = new Date();
  top_date: any = new Date(+new Date - 12096e5);  // 14 days past
  bottom_date: any = new Date(+new Date + 12096e5);  // 14 day future
  range = {
    start_date: this.top_date,
    end_date: this.bottom_date
  }

  generateDays = function (start, end) {
    while(start < end) {
      start.setDate(start.getDate() + 1);
      this.appointments[start.toISOString().slice(0, 10)] = [];
    }
  };

  fillDays = function () {
    this.appointmentService.all(this.range).map(res => res.json()).subscribe(
      data => {
        for (var appointment in data) {
          this.appointments[appointment] = data[appointment];
        }
      },
      err => {
        console.log(JSON.parse(err._body));
      }
    );
  };

  constructor(
    public navCtrl: Nav,
    public appointmentService: AppointmentService,
  ) {
    var temp_date: any = new Date(this.top_date);
    this.generateDays(temp_date, this.bottom_date);
    this.fillDays();
  }

  moreFuture(infiniteScroll) {
    setTimeout(() => {
      var temp_date: any = new Date(this.bottom_date);
      this.bottom_date = new Date(+temp_date + 12096e5); // add 14 days
      this.range.start_date = temp_date;
      this.range.end_date = this.bottom_date;
      this.generateDays(temp_date, this.bottom_date);
      this.fillDays();
      infiniteScroll.complete();
    }, 500);
  };
}

.

// index.html
 <ion-content padding>
  {{appointments | json}}
  <ion-list class="calendar-list">
    <div *ngFor="let appointment of appointments | mapToIterable" [id]="appointment.key">
      <ion-item class="day past">
        <ion-avatar class="date" item-left>
          <h1>{{appointment.key | date: 'dd'}}</h1>
          <h2>{{appointment.key | date: 'MMM'}}</h2>
        </ion-avatar>
        <div *ngIf="!!appointments[appointment.key].length">
          <ion-avatar class="inline" text-center padding>
            {{appointments[appointment.key][0].patient.first_name[0]}}{{appointments[appointment.key][0].patient.last_name[0]}}
          </ion-avatar>
          <div class="inline">
            <h2 class="username" text-wrap>
              {{appointments[appointment.key][0].patient.first_name}}
              {{appointments[appointment.key][0].patient.last_name}}
            </h2>
            <p>
              <ion-icon name="clock-gray"></ion-icon>
              {{appointments[appointment.key][0].time_start | date: 'HH:mm'}}
              -
              {{appointments[appointment.key][0].time_end | date: 'HH:mm'}}
            </p>
          </div>
        </div>
      </ion-item>
    </div>
    <ion-infinite-scroll (ionInfinite)="moreFuture($event)">
      <ion-infinite-scroll-content></ion-infinite-scroll-content>
    </ion-infinite-scroll>
  </ion-list>
</ion-content>

Is the reason for the issue due to using an object rather than an array?

Your answers are greatly appreciated :)

Answer №1

The reason for this behavior is due to the fact that you are utilizing a 'pure pipe', which only runs when there is a change in the value or reference it is applied to. Unfortunately, it does not detect changes in object properties. In your particular scenario, the mapToIterable pipe is not able to recognize any modifications happening to the properties of your object. You can learn more about this concept by visiting this link

To resolve this issue, try the following:

@Pipe({name: 'mapToIterable', pure: false})

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

Troubleshooting problem with GZIP in Angular 2 application deployment

I have developed an Angular 2 TypeScript application. I am using Firebase for hosting and Cloudflare for optimizing speed, caching, and security. When checking the browser header, it indicates: accept-encoding:gzip, deflate, sdch, br The app.js file has ...

It seems that there is an issue with the function _co.onBlueprintAdded as it is not

I am encountering an issue with my cockpit.component.ts file in Angular. Here is the code snippet: import {Component, EventEmitter, OnInit, Output} from '@angular/core'; @Component({ selector: 'app-cockpit', templateUrl: '. ...

Integrating @types/arcgis-js-api into an Angular 5 project

Incorporating arcgis-js-api types into my angular5 application has been a challenge. Whenever I attempt to import the types in multiple components, an uncaught reference error occurs: __esri is not defined. I made sure to include arcgis-js-api in the typ ...

The solution to enabling Type checking in this scenario is simple: Begin by addressing the issue of "Not assignable," followed by resolving any

After subscribing to an observable projected by a BehaviorSubject from a service, I encountered the following errors when trying to assign the subscribed value to a local variable: error TS2322: Type '{}' is not assignable to type 'DatosAdmi ...

Having difficulty grasping the reason for the databinding issue in Angular 6

Hey there, I'm relatively new to working with Angular 6 and currently in the process of building my own website using Angular+NodeJs. The interface I'm creating consists of 2 sections each containing 3 buttons. When a button is clicked, it trig ...

Attempting to successfully upload this Angular 7 form to my TypeScript code. Making use of ngForm and [(ngModel)] to achieve this

I am having trouble passing form information using the onSubmit() function. It seems to be undefined when I try to execute it initially. Could there be a syntax error that I'm missing? <form class="gf-formbox" name="credentials" (ngSubmit)="onSubm ...

"Exploring AngularFire Database: Simple ways to retrieve the total number of items in a list

I attempted to utilize angularfire2 in order to develop a function that retrieves the total number of entries in a list within a firebase real-time database. For instance: Retrieve the count of users in '/users'. I am not interested in continuou ...

ESLint not functioning properly on TypeScript (.ts and .tsx) files within Visual Studio Code

After installing the ESLint extension in VSC, I encountered an issue where it was no longer working on the fly for my React project when I introduced Typescript. In the root of my project, I have a .eslintrc file with the following configuration: { "pa ...

What's causing the subscription feature to malfunction in a fresh browser tab?

I am facing an issue with camera entries on an angular website. Whenever I click on an entry, a new window opens to display the camera livestream. However, I am having trouble with the subscribe functionality. Important note: Once the window is open, subs ...

What could be causing the TypeError in Angular when utilizing '$event.target.checked' with mat-checkbox?

While working with Angular mat-checkbox, I encountered an error when trying to use $event.target.checked. The error message stated - "Cannot read property 'checked' of undefined at Object.eval [as handleEvent]". This issue arose while attempting ...

While executing a DELETE operation, TypeORM mistakenly includes a superfluous AND clause in the final query

Edges Table Structure: id | from_node | to_node Performing the operation: node.id = 1 await getManager().delete(Edge, [{ from_node: node.id }, { to_node: node.id }]); Generates the following query: DELETE FROM "edges" WHERE (("from_node" = $1 AND "to_n ...

Tips for Sending an Image, PDF, and Multiple Parameters Simultaneously from an Angular Application to a Node.Js Server

Currently utilizing Angular Material to obtain the position of a draggable image, receiving user input type file (pdf), and storing images in ./assets/emojis/. Successfully sending PDF from Angular to Node using ng2-file-upload and multer. FrontEnd <inp ...

Is there a way to target the mat-icon element using the icon's name in CSS

I have a group of mat-icons that are automatically generated, meaning I cannot assign them ids or classes. The only way to distinguish between them is by their names: <mat-icon role="img">details</mat-icon> <mat-icon role="img ...

Modify the color of the downward arrow within a dropdown menu

I'm currently working with ngx paginator and I need to customize the CSS styles to appear in white color. Here is the code I've tried: HTML <div class="paginator__footer-select col col-md-3 offset-md-1 "> & ...

The Angular Compiler was found to be the incorrect class instance, causing issues with the project's build process

error snapshot It appears that an incorrect instance of the Angular Compiler was detected, indicating the presence of multiple @ngtools/webpack packages. To verify this, you can use the command npm ls @ngtools/webpack and proceed to remove any duplicate c ...

Tips on implementing pdf-lib in Angular?

I came across the pdf-lib library and am interested in incorporating it into my Angular project. However, I couldn't find any documentation on how to import it specifically for Angular. Can anyone assist me with the process of importing this library ( ...

Angular encountered a ERR_EMPTY_RESPONSE error

Currently, I am developing a web application using C# Web API for the backend and Angular for the frontend. In my backend, I have implemented a User controller and set up a basic GET request in Angular. However, when testing the Angular request, I encounte ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

Utilizing Angular functionality to automatically update state with data retrieved from localstorage after a successful fetch

In my attempt to enhance my application's functionality, I created a custom effect to update state from local storage upon a successful fetch on a page: export const updateStateFromTokensEffect = createEffect( (actions$ = inject(Actions), jwtService ...

Postman is having trouble communicating with an express router and is unable to send requests

Currently, I am experiencing some challenges while trying to grasp the concepts of express and node with typescript, particularly when setting up a router. In my bookRoutes.ts file, I have defined my router in the following manner: import express, { Expre ...