Working with objects in *ngFor in Ionic 2

I am utilizing Ionic 2 and attempting to display the content of a key-value array using an object.

In order to display my collection, I am using a pipe in my HTML. Below is my HTML code:

<ion-list>
    <ion-item *ngFor="let event of this.pdata.array | mapToIterable">Toto</ion-item>
  </ion-list>

This is the code for my pipe :

import {Injectable, Pipe, PipeTransform} from '@angular/core';

type Args = 'keyval'|'key'|'value';

@Pipe({
  name: 'mapToIterable',
  pure: true
})
@Injectable()
export class MapToIterablePipe implements PipeTransform{
  transform(obj: {}, arg: Args = 'keyval') {
    return arg === 'keyval' ? Object.keys(obj).map(key => ({key: key, value: obj[key]})) :
        arg === 'key' ? Object.keys(obj) :
            arg === 'value' ? Object.keys(obj).map(key => obj[key]) : null;
  }
}

Issue : I am setting my 'array' with an async method, but my pipe is only loading once. Therefore, even though my 'array' is not empty, 'Toto' is not being displayed.

The async method is set in a provider. It sets the 'array' after querying a web service. The constructor of my page calls the provider's function to set the 'array' and display the variable in the view.

This is the code for my provider (p-data.ts) :

getDatas() : void {
    let url: string = [MY_URL]
    this.http.get(url).map(res => res.json()).subscribe( res => {
      for (let i: number = 0 ; i < res.events.length ; i++) {
        let object: any = res.events[i].data;

        let data_guid  : string = 'fr_medicalEvent_' + object.id;

        this.array[data_guid] = new CData(data_guid, object.name, object.old);
      }
    }, error => {});
  }

Code for my page .ts file :

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

import {NavController, Platform} from 'ionic-angular';
import {PData} from "../../providers/p-data";
import {DetailsMedicalEventPage} from "../details-medical-event/details-medical-event";
import {PTranslate} from "../../providers/p-translate";

@Component({
  selector: 'page-to-come',
  templateUrl: 'to-come.html'
})
export class ToComePage {


  constructor(public navCtrl: NavController, public pdata : PData, public translate : PTranslate) {
    this.pdata.getDatas();
  }

}

How can I force my pipe to refresh ?

Answer №1

In order to handle a Promise or Observable returned by the pipe, you will need to utilize the |async pipe in the following manner:

 <ion-item *ngFor="let event of this.pdata.array | mapToIterable | async">

update

The issue arises when you make changes to an existing array (this.array[data_guid] = ...). Angular does not detect this alteration and as a result, the view does not get updated. You have a couple of options to address this - either make your pipe impure

@Pipe({name: "...", pure: false})

which can impact performance, or replace the array with a new one after updating it

this.array[data_guid] = new CData(data_guid, object.name, object.old);
this.array = this.array.slice();

although this method may be costly depending on the array's size.

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

What is the reason behind the never return value in this typescript template?

As demonstrated in this example using TypeScript: Access TypeScript Playground type FirstOrSecond<condition, T1, T2> = condition extends never ? T1 : T2 type foo = never extends never ? () => 'hi' : (arg1: never) => 'hi' ...

Top method for sending arguments when utilizing RxJS forkJoin

Hey there! I'm currently working on a service with three functions that I need to execute. To handle this, I've opted for using forkJoin as it allows me to take further action once all responses are received. One of the functions requires one par ...

Defining preset values within a TypeScript model class

Suppose I have a User class and I want to instantiate only predefined 'status'. Is this the optimal approach? Are there any other alternatives? What is the correct way to achieve this? Thank you in advance. export class User { constructor( ...

Issue with ngb-carousel not properly loading upon page refresh within an Angular project

I have integrated ngb-carousel into my Angular application for a basic website. Overall, everything is functioning correctly, but I have noticed that when I refresh the page, the carousel's image takes longer to load compared to the indicators and arr ...

Include an external JavaScript file within a component to display pictures in a web browser using Angular 2

I am developing a website using Angular 2 and need to incorporate a JavaScript file into a component. The goal is for this script to adjust the height of certain images to match the height of the browser window. What is the best way to integrate this scri ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

What could be causing the issue with FindOne not functioning correctly when using TypeORM and MongoDB to find by ID?

Having an issue with typeorm and MongoDB. Attempting to search for a document by Id and encountering unexpected results. When using the syntax const manager = getMongoManager(); const user = await manager.findOne(User, {userId}); I receive an undefined re ...

Generating observables from form submission event

Note: I am completely new to Angular and RXJS. Currently, I am working on a simple form where I want to create an observable. The goal is to listen for submit events and update a value within the component. However, I keep encountering an error message sa ...

Creating a CSS animation to slide a div outside of its container is

I currently have a flexbox set up with two adjacent divs labeled as DIV 1 and DIV 2. By default, both DIV 1 and DIV 2 are visible. DIV 2 has a fixed width, occupying around 40% of the container's width. DIV 1 dynamically adjusts its width to ac ...

NestJS API experiencing issues connecting to MongoDB due to empty index keys

My goal is to create an API with NestJS using TypeORM. Initially, I had set up the API to work with Postgres, but now I need to migrate it to MongoDB. After making the necessary changes, the connection is established successfully. However, I encounter an ...

Challenge with JWT Tokens

In my application, I am utilizing a Node.JS express backend along with an Angular 4 frontend. The user ID is stored in JWT tokens, which do not expire. Here is the scenario: The user logs in. A JWT Token is generated and signed (containing the user ID). ...

How to submit a form in Angular2 without reloading the page

I have a straightforward form to transmit data to my component without refreshing the page. I've tried to override the submit function by using "return false," but it doesn't work as expected, and the page still refreshes. Here is the HTML: ...

Tips for importing a package in Angular 2 with Visual Studio 2015

After running npm install --save camelCase, I have successfully installed the package. Now, I am looking to utilize it in my project along with TypeScript version 2.0.3. In order to import the package, I added the following line: import * as camelcase ...

Handling functions in Ant Design Select component with TypeScript types

I have a query. Antd offers a custom Select input with functions like onSelect, onChange, etc. I am utilizing the onSelect function which requires the following arguments: (JSX attribute) onSelect?: ((value: string | number | LabeledValue, option: OptionDa ...

Retrieving Names Using Angular2 Dynamic Component Loader to Render a Component List

I am currently utilizing a Dynamic Component Loader to present a series of components using *ngFor: <div [dragula]='"bag-one"' [dragulaModel]='types'> <div *ngFor="let component of types; let i = index"> <dcl-wrapp ...

Error message displayed indicating script not found after executing yarn tsc within a Docker container

Using docker, I successfully built my project by running yarn tsc. However, when I executed docker run -p88:5011 accounts2 I encountered the following error: PM2 error: Error: Script not found: /home/accounts/dist/server/index.js. This error occurs despit ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

Tips for transferring the value of a text box between components bidirectionally in Angular 8

Let's create a scenario where we have two components: login and home. The goal is to capture the value entered in the text box of the login component and pass it to the text box in the home component when the "proceed" button in the login component is ...

What methods can be employed to ensure that external stylesheets are properly loaded within the shadow DOM?

I created a new CSS utility for responsive design and built a documentation site using Angular 16 to showcase its features. To demonstrate the responsiveness, I developed a component with a resizable <iframe> where I embed the demonstration component ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...