Arrange an array within an Angular component

I'm in the process of organizing my list-component made with Angular Material.

<div style="width:30%;">
        <mat-nav-list matSort (matSortChange)="sortData($event)">
            <th mat-sort-header="stuff.name">Name</th>
            <mat-list-item *ngFor="let stuff of vehicleDetails">
                <button matLine (click)="updateInfo(stuff.id)"> {{ stuff.name }} </button>
                <button mat-icon-button id="btn" *ngIf='check(stuff.alarm)' matTooltip="{{stuff.alarm[tooltipIndex(stuff)]?.timestamp}} - {{stuff.alarm[tooltipIndex(stuff)]?.description}}">
                    <mat-icon>info</mat-icon>
                </button>
            </mat-list-item>
        </mat-nav-list>
    </div>

The list content consists of various vehicle names extracted from my vehicleDetails array, which stores information like name and id. Currently, I am working on implementing sorting functionality based on the name property. The functions below are intended to assist me in achieving this goal:

 export class VehiclelistComponent implements OnInit, AfterViewChecked
 {

vehicleDetails: VehicleDetail[] = [];
sortedVehicleDetails: VehicleDetail[];

sortData(sort: Sort) {
    const data = this.vehicleDetails.slice();
    if (!sort.active || sort.direction === '') {
      this.sortedVehicleDetails = data;
      return;
    }
    this.sortedVehicleDetails = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'name':
          return this.compare(a.name, b.name, isAsc);
        default:
          return 0;
      }
    });
  }

  compare(a, b, isAsc) {
    return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
  }

Incorporating ngOnInit and ngAfterViewChecked methods:

ngOnInit() {
    // Initialize vehicles
    this.getVehicleDetails();

   }

  ngAfterViewChecked() {
    this.sortedVehicleDetails = this.vehicleDetails.slice();
  }

Seeking solutions for sorting by different properties besides just the name field. How can I enhance the current sorting mechanism?

Answer №1

Make sure to identify the property by which the object array should be sorted.

Here's an example:

  sort(value: any[], criteria: SortCriteria): any[] {        
    if (!value || !criteria)
      return value;

    let p: string = criteria.property;

    let sortFn:(a: any, b: any) => any = (a, b) => {
      let value: number = 0;
      if (a[p] === undefined) value = -1;
      else if (b[p] === undefined) value = 1;
      else value = a[p] > b[p] ? 1 : (b[p] > a[p] ? -1 : 0);
      return criteria.descending ? (value * -1) : value;
    };

    value.sort(sortFn);
    return value;
  }

Define SortCriteria as follows:

interface SortCriteria {
  property: string;
  descending?: boolean;
}

You can also implement a pipe for direct usage in a template

Check out Stackblitz

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

A guide to retrieving data from a service in an Angular component

Hello, I am new to Angular and seeking help with my angular service and component. Specifically, I have a Register component and a Country service. My goal is to retrieve all countries from an API and display them in a form while also making this country ...

Navigating through pages: How can I retrieve the current page value for implementing next and previous functions in Angular 7?

Greetings, I am a new learner of Angular and currently working on custom pagination. However, I am facing difficulty in finding the current page for implementing the next and previous functions. Can anyone guide me on how to obtain the current page value? ...

What is the injection token used for a specialized constructor of a generic component?

I created a versatile material autocomplete feature that I plan to utilize for various API data such as countries, people, and positions. All of these datasets have common attributes: id, name. To address this, I defined an interface: export interface Auto ...

"Exploring the capabilities of Angular 4 Material for seamless page navigation

I am brand new to Angular 4 using Material Design 2. I have a simple inquiry regarding this topic. My code is in app.component.html, which displays a few mat-card components. When clicking on any link inside the mat-card component, it should switch the e ...

The dropdown cannot be disabled because it is being passed as an input parameter

We are currently utilizing PrimeNG along with Angular 15. Scenarios: According to the requirements, we need the ability to disable the PrimeNG dropdown control based on a selection. Problem: The disabled property of <p.dropdown> is not functioning ...

Switching from a Promise to an Observable using React-Redux and TypeScript

I am struggling to grasp the concept of storing a Promise response into Redux. I believe finding a solution to this issue would greatly benefit me. Currently, I am utilizing a library that returns a Promise, and I wish to save this response - whether it i ...

Creating dynamic components from JSON elements does not trigger a rerender of components within an array

Imagine having a simplified input structure like this: [ { type: "text", text: "how are you {name}" }, { type: "input", input: "name" }, { type: "text", text: "good to ...

Unable to bind to ngModel as it returned as "undefined" in Angular 8

Whenever I bind a property to ngModel, it consistently returns undefined <div> <input type="radio" name="input-alumni" id="input-alumni-2" value="true" [(ngModel) ...

Ways to resolve NPM dependency conflicts

Attempting to set up all the necessary npm packages for the AWS sample demo found at https://github.com/aws-samples/amazon-chime-sdk-classroom-demo on my laptop has been a bit challenging. Every time I try to run npm install I can't help but wonder i ...

specialized registration process with auth0 in Angular

I am attempting to enhance the user information in a single call. The process involves first signing up with a username and password on Auth0, followed by adding additional userinfo to the database during the callback phase. However, I am encountering diff ...

Is it possible for me to define TypeScript interfaces to be used in vanilla JavaScript projects within VSCode?

While using the MS VisualCode editor, I am attempting to implement type checking in my Javascript code. I want to maintain the flexibility of Javascript while also benefiting from type checking interfaces and data structures. Based on the vscode documenta ...

The Influence of Getter Performance in Angular Templates

As I delve into an existing Angular application, I've noticed a pattern where values used in templates across many components are actually properties that are being accessed through getters and setters without any additional logic: <input type="nu ...

Building the Android release version of an Ionic Cordova app using the command `ionic cordova build android –prod –release` may encounter a failure when it

Having an issue with Ionic 3. Whenever I use cordova build android --prod --release, the APK shows a white screen after splash. Alternatively, when using ionic cordova build android --prod --release, I encounter the following error. https://i.stack.imgur. ...

Click to alter the style of an <li> element

I'm currently using Angular CLI and I have a menu list that I want to customize. Specifically, I want to change the background color of the <li> element when it is clicked. I am passing an id to the changeColor() function, but unfortunately, I a ...

Progressive File Upload in ASP.NET Core 2.0 and Angular 4.3: A Seamless Integration

Is there a way to utilize the latest Angular 4.3 HttpClient to handle file uploads and retrieval in an ASP.NET Core 2.0 Controller, all while providing live upload progress updates to the client? ...

Using Angular2 animations (specifically transform animations) on an iPhone 6s may result in unexpected behavior

I am interested in utilizing Angular2's Animation to create an animation similar to the following: transition('out => arise', [ style({ 'transform': 'translateY(-50px)', '-webkit-transform&a ...

Guide on retrieving the interface property name or key name as a string in Typescript

Currently, I am utilizing the API of Slack and encountering situations where I send JSON requests containing strings that return as property names later on. I want to create an interface where I can send one of its property names as a string and receive t ...

When combining arrays in PHP results in an empty result

I have a scenario where I am populating an array with years extracted from page publish dates. To ensure that only unique years are included, I apply a filter. However, when attempting to add a string ('Any') as the first element for a select box ...

Input a value to request in the Mssql node

I am using angular2 and mssql to establish a connection with SQL Server. This is my code snippet: var express = require('express'); var app = express(); var sql = require("mssql"); // database configuration var config = { user: 'sa&ap ...

Incorporating dynamic dependency injection in Angular 2 through the use of @Input()

Let's consider a scenario where an Angular 2 component-directive needs to dynamically determine the injected dependency it uses based on an @Input(). For example, I would like to be able to specify <trendy-directive use="'serviceA'"> ...