Can anyone assist me with creating a custom sorting pipe in Angular 2?

 *ngFor="let match of virtual | groupby : 'gameid'

I have this code snippet that uses a pipe to group by the 'gameid' field, which consists of numbers like 23342341.

Now, I need help sorting this array in ascending order based on the gameid. Can anyone provide me with the necessary code for this?

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

/**
 * Custom GroupbyPipe implementation.
 */
@Pipe({
  name: 'groupby',
})
export class GroupbyPipe implements PipeTransform {
  /**
   * Transform function to sort an array by a specific property.
   */
   transform(array: Array<string>, args: string): Array<string> {
        if (array !== undefined) {
            array.sort((a: any, b: any) => {
                if (a[args] < b[args]) {
                    return -1;
                } else if (a[args] > b[args]) {
                    return 1;
                } else {
                    return 0;   
                }
            });
        }
        return array;
    }

}

This is my customized pipe for sorting arrays based on the specified property.

I tried finding solutions on Google but none of them worked. Could someone guide me on how to successfully sort my array using the pipe according to the gameid (integer) property?

Answer №1

To ensure detection of changes in the local data, I have incorporated the changeDetectorRef. In some cases, modifications made within a subscribe block may not be reflected immediately. Below is a snippet of my code showcasing the implementation of both changeDetectorRef and slice functions. Feel free to utilize them by referring to my working version available here

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 term:string = "";
  topics = [
    {type:"NonFiction", name:"Titanic", num:2},
    {type:"Fiction", name:"Avatar", num:1},

    {type:"Tragedy", name:"MotherIndia",num:5},
  ];
  constructor(public ref : ChangeDetectorRef) { }

  ngOnInit() {
    this.addTopic();
  }

  addTopic(){
    setTimeout(()=>{
      console.log("triggered");
      this.topics.push({type:"share", name:"MotherIndia",num:3});
      this.topics=this.topics.slice();
      this.ref.detectChanges();
    },5000)
  }
}

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

The 'data' property is absent in the 'never[]' type, whereas it is necessary in the type of product data

Hello, I am new to TypeScript and I'm struggling with fixing this error message: Property 'data' is missing in type 'never[]' but required in type '{ data: { products: []; }; }'. Here is my code snippet: let medias :[] ...

Angular2 fire fails because the namespace 'firebase' does not export the member 'Promise'

I recently set up Angular 2 Fire on my project. "angularfire2": "^5.0.0-rc.0", Now, in my root module (app module), I have the following setup: export const firebaseConfig = { apiKey: "mykey", authDomain: "....", databaseURL: "...", projectId: ...

Leverage the power of forkJoin in JavaScript by utilizing objects or sourcesObject

I'm currently facing an issue with my code snippet below: getInformations().subscribe( informations => { let subs = []; for (const information of informations) { subs.push(getOtherDetails(information.id)); } ...

Storing the data retrieved from an HTTP GET request in Ionic 2

I've been working on developing an app and have successfully set up an event provider. Utilizing the Eventbrite API, I am able to retrieve a list of events taking place in a specific city. However, I'm facing challenges when attempting to execute ...

ReactJS - Opt for useRef over useState for props substitution

Presented below is my ImageFallback component, which serves as a backup by displaying an svg image if the original one is not available. export interface ImageProps { srcImage: string; classNames?: string; fallbackImage?: FallbackImages; } const Im ...

Ways to swap out element within ViewContainerRef in Angular

I am currently expanding my knowledge of Angular and I have encountered a challenge regarding dynamically creating components and swapping them within a single container. Here is the setup: <ng-container #container></ng-container> Here are the ...

Make TypeScript parameter optional if it is not supplied

I am working with an interface that defines scenes and their parameters: export interface IScene<R extends string> { path: R; params?: SceneParams; } The SceneParams interface looks like this: export interface SceneParams { [key: string]: s ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

Incorporating an external SVG file into an Angular project and enhancing a particular SVG element within the SVG with an Angular Material Tooltip, all from a TypeScript file

Parts of the angular code that are specific |SVG File| <svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="950" height="450" viewBox="0 0 1280.000000 1119.000000" preserveAspectRatio= ...

What causes the module declaration in the .d.ts file to fail in an Angular application?

I have recently created a file named global.d.ts within the src folder and it contains the following content: declare module 'ol-contextmenu'; Despite my efforts, placing the file in the root directory or in node-modules/@types did not solve the ...

Get started with adding a Typescript callback function to the Facebook Login Button

I am in the process of implementing Facebook login into my Angular7 application using Typescript. Although I have successfully integrated Facebook's Login Button plugin for logging in, I am facing issues with providing a callback method to the button& ...

Selecting an option with a specific index in Angular 2 RC2

I have encountered a situation where the select options are non-unique, with the same value representing different things. This is how our data is structured and I need to work within those constraints. <select id="mySelect"> <option value = "1 ...

Is it possible to pass a prop from a parent container to children without knowing their identities?

I am currently working on a collapsible container component that can be reused for different sections of a form to display fields or a summary. Each container would include a Form object passed as a child. Here is the basic structure of my code: function C ...

Encountering an uncaughtException: Error stating that the module '....nextserverapphomelibworker.js' cannot be located while attempting to utilize pino.transport in Next.js

I recently set up a Next.js project with typescript using create-next-app. Opting for Pino as the logging library, recommended by Next.js, seemed like the logical choice. Initially, when I utilized Pino without incorporating its transport functionality, e ...

What methods can TypeScript employ to comprehend this situation?

There's an interesting scenario when it comes to assigning a variable of type unknown to another variable. TypeScript requires us to perform type checking on the unknown variable, but how does TypeScript handle this specific situation? It appears that ...

The process of modifying all interface values in typescript

Suppose I have a function that accepts a dynamic object as a parameter. const fun = <IValues>(values: IValues) => // IValues = {a: '', b: ''} My intention is to use that object and create a clone with the same keys but differ ...

Accessing the NestJS DI container directly allows for seamless integration of dependency

I have been using NestJS for the past 4 months after working with PHP for 5 years, mainly with Symfony. With PHP, I had the ability to access the compiled DI container and retrieve any necessary service from it. For example, in an application with service ...

What is the most efficient way to remove all typed characters from fields when clicking on a different radio button? The majority of my fields share the same ngModel on a separate page

Is there a way to automatically clear all typed characters in form fields when switching between radio buttons with the same ngModel on different pages? I noticed that the characters I type in one field are retained when I switch to another radio button. ...

Combining two streams in RxJS and terminating the merged stream when a particular input is triggered

I am currently developing an Angular application and working on implementing a system where an NGRX effect will make requests to a service. This service will essentially perform two tasks: Firstly, it will check the local cache (sqlite) for the requested ...

Trouble encountered while configuring and executing Electron combined with React, Typescript, and Webpack application

I am currently in the process of migrating my Electron application from ES6 to Typescript. Despite successfully building the dll and main configurations, I encounter a SyntaxError (Unexpected token ...) when attempting to run the application. The project c ...