Arranging table columns in Angular 2

Having trouble organizing the columns of my table using Angular 2

The transform code for the pipe is as follows:

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

@Pipe({ name: 'orderBy' })
export class OrderByPipe implements PipeTransform {

  transform(records: Array<any>, args?: any): any {

    return records.sort(function(a, b){
      if(a[args.property] < b[args.property]){
        return -1 * args.direction;
      }
      else if( a[args.property] > b[args.property]){
        return 1 * args.direction;
      }
      else{
        return 0;
      }
    });
  };
}

I've created a sorting function in my component.ts file like this:

sort(property){
    this.isDesc = !this.isDesc; //change the direction
    this.column = property;
    this.direction = this.isDesc ? 1 : -1;
    //this.sort(this.column);
};

This is how the HTML structure looks like:

<th class="cell-width-header title" (click)="sort(sellerNo)">
            Seller No
            <i class="fa" [ngClass]="{'fa-sort': column != 'sellerNo', 'fa-sort-asc': (column == 'sellerNo' && isDesc), 'fa-sort-desc': (column == 'sellerNo' && !isDesc) }" aria-hidden="true"> </i>
          </th>




 <tr *ngFor="let x of selectedData  | orderBy: {property: column, direction: direction}">


            <td>{{x.sellerNo}}</td>

However, upon loading the page, I encounter the following error:

zone.js:522 Unhandled Promise rejection: Error in ./FundingRequestComponent class FundingRequestComponent - inline template:208:14 caused by: Cannot read property 'sort' of undefined ; Zone: angular ; Task: Promise.then ; Value: ViewWrappedError {__zone_symbol__error: Error: Error in ./FundingRequestComponent class FundingRequestComponent - inline template:208:14 cau……} Error: Error in ./FundingRequestComponent class FundingRequestComponent - inline template:208:14 caused by: Cannot read property 'sort' of undefined at ViewWrappedError.ZoneAwareError (http://localhost:4200/polyfills.bundle.js:6688:33) at ViewWrappedError.BaseError [as constructor] (http://localhost:4200/vendor.bundle.js:94913:16) at ViewWrappedError.WrappedError [as constructor] (http://localhost:4200/vendor.bundle.js:94978:16) at new ViewWrappedError (http://localhost:4200/vendor.bundle.js:96282:16)

Answer №1

It seems like the data (selectedData) is being loaded asynchronously in the component's class, which is why initially it may be undefined until it is returned from the service.

To handle this situation, there are a few approaches you can take:

1. Initialize the data within the component

You can set the selectedData property of the class to an empty array so that when the pipe runs, it will have an array to work with even if the backend data has not yet been retrieved.

export class MyComponent {
    selectedData = [];
}

2. Use *ngIf to control the template rendering

Avoid rendering the part of the template with the pipe until the array is available.

<table *ngIf="selectedData">
  <!-- ... -->
  <tr *ngFor="let x of selectedData | orderBy: {property: column, direction: direction}">
</table>

3. Ensure the pipe handles empty input gracefully

This is a recommended solution as it eliminates the need for special logic each time the pipe is used.

@Pipe({ name: 'orderBy' })
export class OrderByPipe implements PipeTransform {
  transform(records: Array<any> = [], args?: any): any {
    /* ... */

Notice how the records = [] sets a default value in the transform method parameter?

It's good practice to always make pipes ready to handle no initial input. It simplifies usage and prevents potential issues.

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

There seems to be an issue with the function code error when calling it within the

When I attempt to run my code in this way, I encounter a compile time error stating that the expression statement is not an assignment or call... (within the else statement). What am I missing here to get it to work? I've made numerous attempts to ad ...

What is preventing me from accessing the $sceProvider?

Struggling to implement a filter using $sceProvider to decode HTML tags. Here's my current code structure: myApp.filter('decodeHtml', function($sce) { return function(item) { return $sce.trustAsHtml(item); }; However, upon integrating ...

Using Express.js, the require() method is called, followed by a function that takes

I'm relatively new to Node.js and Express. While browsing tutorials and examples, I came across the following code snippet inside app.js: var router = require('./router')(app); I'm curious about the purpose of this line of code. What ...

Listening for Events on Multiple Groups of Radio Buttons

How can a dynamic Javascript/JQuery event listener determine which radio button group has been clicked and retrieve the value of the checked element? If there are two radio button groups, how would you differentiate between them? How could this be achieved ...

Utilizing Threejs to implement dynamic text labels

Recently, after reading a discussion on stackoverflow, I decided to incorporate labels into my canvas. To achieve this, I created a second scene and camera to overlay the labels on top of the first scene. this.sceneOrtho = new THREE.Scene();//for labels t ...

Limit pasted content in an Angular contenteditable div

Is there a way to limit the input in a contenteditable div? I am developing my own WYSIWYG editor and want to prevent users from pasting content from external websites and copying styles. I want to achieve the same effect as if the content was pasted into ...

Guide on how to perform a POST request within a service worker?

I am faced with the challenge of sending a POST request to the back-end every time a client clicks on a Push notification from the front-end, in order to confirm that the client has received the notification. Here is the system I currently have in place f ...

Struggling with jQuery UI Draggable 1.10.3 bug in Firefox: Cursor center not detected when scrolling window

Before version 1.10.3, possibly 1.9.x, I didn't encounter this issue. However, after updating to jQuery UI 1.10.3, Firefox seems to have trouble locating the center of the cursor on the draggable plugin when the window is scrolled down. This problem ...

What is the best way to filter out specific data fields from console.log in JavaScript?

When working with Java, I often use lombok to exclude certain fields from being printed. For instance, the @ToString.Exclude annotation can be used to prevent printing the user token. import lombok.ToString; public class TokenResponse { @ToString.Excl ...

Issues with extensions during the Angular 9 Ivy compilation process

Good day! After upgrading a v8 project to v9, I encountered some errors related to extensions in the compiler. These errors are not present in another project that I also recently upgraded. The extensions, which are basic for constructors and prototypes, ...

A guide on importing images into a CSS file with Reactjs

Currently, I am utilizing Reactjs (Nextjs) and have placed my images folder within the "public" directory. In my "style.css" file, I adjusted the path for the image, but unfortunately it is not displaying. Can you please help me identify where I may have ...

Guide on populating a table with user input using jQuery and ajax

For the past few days, I've been attempting to populate a table using jQuery and ajax based on search results, but unfortunately, it's not working out for me. Below is the HTML code snippet: <form class="form"> <div class="form-gro ...

What is the correct syntax for implementing scrollTop and transform CSS effects in jQuery?

I find myself in a bit of a quandary, as this question may seem rather simple but it's causing me some confusion. I'm trying to navigate the CSS transform syntax within a jQuery script that calculates window height. Here is the code in question: ...

When utilizing Jest, the issue arises that `uuid` is not recognized as

My current setup is as follows: // uuid-handler.ts import { v4 as uuidV4 } from 'uuid'; const generateUuid: () => string = uuidV4; export { generateUuid }; // uuid-handler.spec.ts import { generateUuid } from './uuid-handler'; de ...

NodeJS: The module failed to automatically register itself

Exploring the capabilities of IBM Watson's Speech to Text API, I encountered an issue while running my NodeJS application. To handle the input audio data and utilize IBM Watson's SpeechToText package, I integrated the line-in package for streami ...

Information is not appearing in the table

I'm having trouble displaying data in a table format. The issue arises when I try to fetch data from a JSON file using a custom service. The fetched data is then inserted into the $rootScope object. However, when I preview the view, it appears blank ...

Is it possible to disable a function by clicking on it?

I currently have a website that is utilizing the following plugin: This plugin enables an image to be zoomed in and out through CSS transforms, with default controls for zooming in and out. My goal is to incorporate a reset button that returns the image ...

When the ajax response comes in, my javascript code seems to suddenly stop

After sending a POST request, my JavaScript suddenly stops working for some unknown reason. Here's the situation: I visit my webpage, fill out the form, and then click 'Click me' : Upon clicking OK in the alert popup, I see the expected ou ...

Fixing a compilation error when attempting to paste text into a file with Selenium Webdriver

I am new to using Selenium webdrivers and encountering a compilation error with the code below. Can anyone provide some assistance? My goal is to save a message into a file rather than displaying it on the console. testResultFile="C:\&b ...

Utilizing both a named function and an arrow function as event handlers in React

Can you spot the issue in the code snippet below? export default function App() { const [count, setCount] = useState(0); return ( <div className="App"> <h2>{count}</h2> <button onClick={() => { ...