Using an asynchronous pipe filter with the ngFor loop in Angular 2 for efficient data

I have a JSON array that I need to iterate through in order to display data using an NGfor Loop. My goal is to apply filters after the data has been loaded to refine the results. The issue I am facing is that my pipe filter is returning 'cannot read property of undefined'. What mistake am I making? To simplify, I have omitted the http Request to fetch data as well as the return logic on the pipe statement.

// component 
import { Observable } from 'rxjs/Rx';
currentData:any = httpRequest; // Simplified  

// html 
<div *ngFor="let item of currentData | async | datePipe; let i = index">
 //display content
</div>

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

@Pipe({
  name: 'datePipe'
})
export class DatePipe implements PipeTransform {

  transform(time:any []): any[] {
    console.log(time);
    return time.filter(it => it["createDt"] != -1); // Simplified

  }

}

*Updated fix *

   // html 
    <div *ngIf="currentData?.length > 0">
      <div *ngFor="let item of currentData | datePipe; let i = index">
        //display content
      </div>
    </div> 

   //pipe 
    transform(time:any): any {
     for(let key of time){
        console.log(key.somevalue);
     }
  }

Answer №1

   // HTML code 
    <div *ngIf="currentData?.length > 0">
      <div *ngFor="let item of currentData | datePipe; let i = index">
        // Display the content here
      </div>
    </div> 

   // Custom pipe example 
    transform(time:any): any {
     for(let key of time){
        console.log(key.somevalue);
     }
  }

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

Creating a Record instance consisting of a specific key and its corresponding value

Sorry for the complexity, I've struggled to simplify this further. Feel free to update the question title for more specificity. I aim to define a foundational data type structure: type AbstractBaseTypes = { [key: string]: { inputTypes ...

Fetch data in JSON format from a specified URL

I have been attempting to fetch a JSON from a specific URL. Here is my current code snippet: <script> var co2; $(document).ready(function(){ alert("0"); $.getJSON(url,function(result){ var jsonObject = result; alert(result); ...

Exploring the art of transforming a string into JSON

I am looking to transform an ansible-init file into JSON format. Here is the code snippet I used from the common_shared file: [sql] x.com [yps_db] y.com [ems_db] c.com [scc_db] d.com [all:vars] server_url="http://x.com/x" app_host=abc.com ser ...

Error with scoped slot typing in Vue3 using Vite and Typescript

I am currently working on a project using Vue3, Vite, and TypeScript as the devstack. I encountered an error related to v-slot that reads: Element implicitly has an 'any' type because expression of type '"default"' can't ...

What is the way to obtain loading start/end events while using a loader widget in conjunction with an asynchronous Firebase request (observable)?

I have implemented AngularFire in the following manner: constructor(private afDb: AngularFireDatabase) { allRRs$ = this.afDb.list(`research_reports-published/`).valueChanges(); } The variable allRRs$ is an observable that I am utilizing in my templat ...

How to attach input to function invocation in Angular 2

Can we connect the @Input() property of a child component to a parent component's function call like this: <navigation [hasNextCategory]="hasNextCategory()" [hasPreviousCategory]="hasPreviousCategory()" (nextClicked)="next ...

"I am looking for a way to receive a response from a loopback in Angular7

Currently, I am utilizing angular7 with loopback. While I can successfully retrieve data, I am unsure how to receive error messages and response statuses. It would be helpful for me to understand what my response code is at the time of the request. Output ...

What is the procedure for inserting a new row alongside an existing row with the same key in a JSON file

Two variables contain JSON data as shown below. var firstJson= [{ name: 'AAA', id: 100}, { name: 'BBB', id: 100 }, { name: 'CCC', id: 101}, { name: 'DDD', id: 102} ] var secondJson= [ { name: ...

Crafting a dynamic HTML template in Angular using template literals and the *ngFor directive

I've been developing a toast component that accepts HTML tags as strings. This requires me to iterate through the errorMsgs array below and dynamically build a list. However, I'm currently facing an issue where the *ngFor loop inside it is iterat ...

I am receiving an undefined response from Cheerio when attempting to fetch JSON data

My goal is to create a web scraper and I have successfully downloaded the HTML. Now, with this code snippet, I am attempting to extract the title from my HTML: fs.readFile(__filename.json , function (err, data) { if(err) throw err; const $ = cheerio.load ...

How can I effectively use gulp-sourcemaps in an Angular application using the IIFE pattern? Can someone confirm if my understanding of sourcem

Today marks my first attempt at working with exporting source maps through my gulp builds. I am currently using angular 1.4.x and we have implemented the following pattern: (function() { 'use strict'; var thing = (function() { func ...

What strategies can be used to address inconsistencies between the type system and runtime behavior?

I have created a unique TypeScript type called Awaitable<T> with the goal of ensuring that Awaited<Awaitable<T>> is always equal to T. export type Awaitable<T> = | (T extends Record<'then', Function> ? never : T) ...

Incorporating Precision to Decimal Numbers in TypeScript Angular

Having some trouble with this issue and I've tried various solutions without success. This problem is occurring within an Angular project. The requirement is to always display a percentage number with two decimal places, even if the user inputs a who ...

React Typescript: excluding a property in a higher order component

Is it possible to write Typescript type definitions that properly expose the Props type of a component created by a HOC? I want to infer the type of props of the wrapped component and remove any properties provided by the HOC. For example, if we have a HO ...

The error message is: "Cannot access property 'up' of an undefined object within the material UI library using theme.breakpoints."

I am encountering difficulties with the export of makeStyles. Below you can find my code and configuration: import SearchField from "../SearchField"; import { TextField, Select, useMediaQuery, Grid, Button, Box, Fade } from '@material-ui/core&ap ...

What is the best way to change a string into JSON format within Angular?

Embarking on processing the string below: const json = '{"list":"[{"additionalInformation": {"source": "5f645d7d94-c6ktd"}, "alarmName": "data", "description": "Validation Error. Fetching info has been skipped.", "eventTime": "2020-01-27T14:42:44 ...

The implementation of adding a JSON header in Slim framework seems to be malfunctioning

Hey there, I've been working with the slim framework to create a JSON API. Everything is functioning well, except for the headers displaying as text/html. The documentation mentions using the withHeader function: $app = new \Slim\App; $app- ...

I'm having trouble grasping the issue: TypeError: Unable to access the 'subscribe' property of an undefined object

I've been working on a feature that involves fetching data from API calls. However, during testing, I encountered some errors even before setting up any actual test cases: TypeError: Cannot read property 'subscribe' of undefined at DataC ...

Revising Function Templates in Angular's UI Bootstrap Pagination

In my application, I am utilizing Angular UI Bootstrap for pagination. Specifically, I am interested in customizing the functions for First/Last and Previous/Next buttons. My attempt to change the function of the Last button to call "changePage" instead o ...

What is the reason for not modifying the filtered and sorted data?

I am currently working on implementing filter options for an item list, but I am facing an issue where the filtering does not work when selecting dropdown options. Array in App.jsx const cameraShowList=[ {id:1,model:"Canon",title:"Canon ...