What is the best way to organize checkboxes (either checked or unchecked) within a mat-table?

https://i.stack.imgur.com/cDQY7.png

            <ng-container matColumnDef="scheduled">
                <th  mat-header-cell mat-sort-header *matHeaderCellDef> Scheduled </th>
                <td mat-cell *matCellDef="let station">
                  <button mat-icon-button [disabled]="" (click)="getSchedules()">
                  <irg-checked-status [checked]="getCheckedStatus(station)"></irg-checked-status>
                </button>
                </td>
              </ng-container>

I am looking to implement sorting for this column based on checkbox selection status.

Answer №1

When it comes to sorting, the location of where you do the sorting matters. The recommended approach is to perform sorting on the backend for efficiency purposes. However, if you need to conduct sorting on the frontend, you can follow the basic example provided below:

import { Component } from "@angular/core";
import { Sort } from "@angular/material/sort";

export interface DataItem {
  id: string;
  scheduled: boolean;
}

/**
 * @title Sorting overview
 */
@Component({
  selector: "sort-overview-example",
  templateUrl: "sort-overview-example.html",
  styleUrls: ["sort-overview-example.css"],
})
export class SortOverviewExample {
  items: DataItem[] = [
    { id: "1", scheduled: true },
    { id: "2", scheduled: false },
    { id: "3", scheduled: true },
    { id: "4", scheduled: false },
  ];

  sortedData: DataItem[];

  constructor() {
    this.sortedData = this.items.slice();
  }

  sortData(sort: Sort) {
    const data = this.items.slice();
    if (!sort.active || sort.direction === "") {
      this.sortedData = data;
      return;
    }

    this.sortedData = data.sort((a, b) => {
      const isAsc = sort.direction === "asc";
      switch (sort.active) {
        case "id":
          return compare(a.id, b.id, isAsc);
        case "scheduled":
          return compareBool(a.scheduled, b.scheduled, isAsc);
        default:
          return 0;
      }
    });
  }
}

function compare(a: number | string, b: number | string, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

function compareBool(a: boolean, b: boolean, isAsc: boolean) {
  return a === b ? 0 : isAsc ? (a ? -1 : 1) : a ? 1 : -1;
}

In summary: compareBool will prioritize sorting true values first when isAsc is set to true, and vice versa for false values.

Happy sorting! ;)

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

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

execute the node application using the .desktop file

Hello, I am attempting to launch an application in Linux by double-clicking it. I have come across the .desktop file as a solution (I need this method because the app will be deployed on a Raspberry Pi and users prefer not to use the terminal). Here is wha ...

Error in refreshing the deployment package of angular 4 on an Apache server

At the moment, my Angular application runs on an Apache server at the 'http://localhost' root or index page. However, when I refresh the inner page 'http://localhost/dms-data/summary-of-findings', the browser displays Page Not Found T ...

Elevate the Appearance of Material UI Elements with custom CSS Sty

I am currently facing an issue while trying to customize the styling of a Material UI component using CSS. Here is the code snippet: <IconButton className="my-class"> <Close /> </IconButton> CSS: .my-class { float: right ...

Customize the appearance of parent components based on the content of their child elements

I am currently working on a component that contains multiple instances, each with its own unique internal component (acting as a modal wrapper). I need to customize the size of each modal instance independently. How can I achieve this customization when th ...

How to access elements by their class name in Angular

Recently, I encountered a situation with this specific span element: <span *ngFor="let list of lists[0].question; let i = index" id="word{{ i }}" (click)="changestyle($event)" class="highlight"> {{ list}} < ...

Unusual behavior of Typescript with Storybook's addon-docs

I'm trying to integrate storybook addon-docs into my TypeScript React project. Everything seems to be almost working, but I've noticed that the file name is affecting how the props type table gets rendered. Here is my file structure: src - Butto ...

Understanding the tsconfig.json file in an Angular project

I encountered the following error in my tsconfig.ts file: 'No inputs were found in config file 'c:/Projects/Angular2//src/tsconfig.json'. Specified 'include' paths were '["src/**/*.ts"]' and 'exclude' paths ...

The switchMap function is sending back a single item

I'm having an issue with switching the observable using the switchMap operator: return this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, { query: { orderByChild: 'deleted', equalTo: false } }) .ma ...

Expo + tRPC: Oops! Looks like the application context couldn't be retrieved. Don't forget to wrap your App inside the `withTRPC` HoC for

I'm currently working on a straightforward tRPC server setup: // server.ts import { initTRPC } from "@trpc/server"; import { z } from "zod"; const t = initTRPC.create(); export const appRouter = t.router({ greeting: t.procedu ...

Can storing JWT in the windows object be considered a secure method for easy retrieval when required?

I have received an access token (JWT) in the URL. For example: . Is it secure to save this token in the window object? For instance: window.jwt = Token If so, how can it be utilized (extracting the JWT from the Window object and carrying out subsequent ...

Increase the size of the angular material accordion

I am dealing with a situation where I have 2 different accordion components on the same page. Each accordion contains multiple expansion panels. My challenge is to close all expanded panels from both accordions and only open the currently selected expans ...

Retrieve the initial token from a union, referred to as an "or list," in Typescript

Is there a way to define a generic type F with the following behavior: type X = F<'a'|'b'|'c'> should result in X being 'a'. And if type X = F<'alpha'|'beta'|'gamma'|'del ...

Why is my input field value not getting set by Angular's patchValue function

I've been attempting to populate an input field using the form group with patchValue(), but for some reason, the input remains empty. Here's a snippet of my code... component.html <form [formGroup]="createStoreForm" (ngSubmit)="createStor ...

Tips for specifying the type when utilizing the spread operator to pass props

type TypeData = { data: { id: string; class: string; name: string; country: string; ew_get_url: string; ew_post_url: string; rocket_id: string; pages: { landing: { h1: string; h2: string; } ...

Can we set a specific length for an array passed in as a prop?

Can we use Typescript to specify the exact length of an array coming from props? Consider the following array of objects: const sampleArray = [ { key: '1', label: 'Label 1', value: 9 }, { key: '2', label: 'Label 2&ap ...

The error message "Cannot bind to 'ngForOf' because it is not recognized as a valid property of the element."

After utilizing NGFor for quite some time, I encountered an unexpected issue in a new application where I received the error message: Can't bind to 'ngForOf' since it isn't a known property of 'div'.' I found it strang ...

Can you explain the concept of BuildOptions in Sequelize?

Despite poring through the sequelize documentation and conducting extensive searches online, I have yet to come across a satisfactory answer: Why is BuildOptions necessary and what impact does it have on the created model? import { Sequelize, Model, Data ...

Having trouble choosing multiple options from autocomplete drop-down with Selenium web-driver in Python

I am currently in the process of automating a webpage built with Angular that features an auto-complete dropdown with numerous elements. My goal is to click on each individual element and verify if it populates all the fields below accordingly. Below is th ...

Encountering issues with obtaining tokens silently using Angular and Microsoft MSAL, resulting in errors AADB2C90077 and AADB2C90205

Seeking assistance in retrieving a token from AAD B2C configuration using Angular9 and microsoft/msal My module setup is as follows; MsalModule.forRoot( { auth: { clientId: "xxxxxxxxxxxxxxxxx", ...