Angular checkbox filtering for tables

I have a table populated with data that I want to filter using checkboxes.

Below is the HTML code for this component:

<div><mat-checkbox  [(ngModel)]="pending">Pending</mat-checkbox></div>
   <div><mat-checkbox  [(ngModel)]="approved">Approved</mat-checkbox></div>
   <div><mat-checkbox  [(ngModel)]="rejected">Rejected</mat-checkbox></div>

<mat-table #table [dataSource]="dataSource">

  <ng-container matColumnDef="PaymentDate">
    <mat-header-cell *matHeaderCellDef> Payment Date </mat-header-cell>
    <mat-cell *matCellDef="let payment"> {{payment.PaymentDate | date: 'dd/MM/yyyy HH:MM'}}  </mat-cell>
  </ng-container>

  <ng-container matColumnDef="Amount">
    <mat-header-cell *matHeaderCellDef> Amount </mat-header-cell>
    <mat-cell *matCellDef="let payment"> {{payment.Amount}} {{payment.Currency}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="StatusDescription">
    <mat-header-cell *matHeaderCellDef> Status Description </mat-header-cell>
    <mat-cell *matCellDef="let payment"  [ngClass]="{'red-color' : payment.StatusDescription == 'Pending' || payment.StatusDescription == 'Rejected', 'green-color' : payment.StatusDescription == 'Approved'}"> {{payment.StatusDescription}} </mat-cell>
  </ng-container>
  <ng-container matColumnDef="Reason">
    <mat-header-cell *matHeaderCellDef> Reason </mat-header-cell>
    <mat-cell *matCellDef="let payment"> {{payment.Reason}} </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
<mat-paginator [length]="5" [pageSize]="5" [pageSizeOptions]="[5, 10, 25]">
</mat-paginator>

I generated sample data to display in the table.

The following is the component code responsible for passing data to the table. Filtering operations based on checkbox selection need to be implemented. For instance, selecting the "rejected" checkbox should only show rows where

payment.StatusDescription == Rejected
.

    import { Component, AfterViewInit, ViewChild } from '@angular/core';
import {MatTableDataSource, MatPaginator} from '@angular/material';
import { PAYMENTS } from "./payments-mock";


@Component({
  selector: 'app-payments',
  templateUrl: './payments.component.html',
  styleUrls: ['./payments.component.scss']
})
export class PaymentsComponent implements AfterViewInit {

  pending = false;
  approved = false;
  rejected = false;


  displayedColumns = ['PaymentDate','Amount','StatusDescription','Reason'];
  dataSource = new MatTableDataSource(PAYMENTS);


  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
  }

}

Here is the mock data used:

import { Payment } from "./payment";

export const PAYMENTS : Payment[] =  [
    {
    'Id': 832321,
    'AccountHolderId': '15651',
    'AccountHolderName': 'Alex Dumsky',
    'PaymentDate': new Date('2015-01-23T18:25:43.511Z'),
    'Amount': 445.12,
    'Currency': 'UAH',
    'Status': 0,
    'StatusDescription': 'Pending',
    'Reason': null
    },
    {
    'Id': 806532,
    'AccountHolderId': '46556',
    'AccountHolderName': 'Dudi Elias',
    'PaymentDate': new Date('2015-02-10T18:25:43.511Z'),
    'Amount': 4511.12,
    'Currency': 'EUR',
    'Status': 0,
    'StatusDescription': 'Pending',
    'Reason': null
    },
    {
    'Id': 7845431,
    'AccountHolderId': '48481',
    'AccountHolderName': 'Niv Cohen',
    'PaymentDate': new Date('2015-04-01T18:25:43.511Z'),
    'Amount': 10.99,
    'Currency': 'USD',
    'Status': 1,
    'StatusDescription': 'Approved',
    'Reason': 'Good Person'
    }
];

Please provide guidance on implementing correct filtering functionality based on the selected checkboxes.

Your assistance is greatly appreciated.

Answer №1

To implement functionality based on checkbox selection events, you can use the following approach:

Example implementation:

mycomponent.component.html

<div>
  <mat-checkbox (ngModelChange)="pendingModelChecked($event) [ngModel]="pending">Pending</mat-checkbox>
</div>

<div>
  <mat-checkbox (ngModelChange)="approvedModelChecked($event) [ngModel]="approved">Approved</mat-checkbox>
</div>

mycomponent.component.ts

ngOnInit() {
  ...
  this.dataSource.filterPredicate = (data, filter: string) => !filter || data.StatusDescription === filter;
}

pendingModelChecked(value) {
  const filter = value ? 'Pending' : null;
  this.dataSource.filter = filter;
}

approvedModelChecked(value) {
  const filter = value ? 'Approved' : null;
  this.dataSource.filter = filter;
}

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

Positioning Multi-level Drop Down Div in Javascript - How to do it efficiently?

I'm currently working on a horizontal menu using CSS and JavaScript with multiple levels. I've implemented a toggle function to show the submenu container, but it's causing the links below it to be pushed down. Is there a way to make the dis ...

Develop a game timer using CreateJS

Looking for advice on the most effective method to create a timer clock using Createjs. I've attempted to reference HTML elements with DOMElement in the past, but encountered difficulties. Essentially, I need to display a timer within a container so p ...

vue mapGetters not fetching data synchronously

Utilizing vuex for state management in my application, I am implementing one-way binding with my form. <script> import { mapGetters } from 'vuex' import store from 'vuex-store' import DataWidget from '../../../../uiCo ...

What is preventing me from using javascript setInterval with a function in a separate external file?

Everything is running smoothly with this code snippet...an alert pops up every 10 seconds <script type='text/javascript'> function letsTest(){ alert("it works"); } var uptimeId = window.setInterval(letsTest, 10000); < ...

Having trouble choosing an option from the dropdown menu with Puppeteer Js

I need help with Puppeteer JS to select the initial element in a dropdown. Any suggestions? Once I input the city name in the text field, I want to choose the first option from the dropdown menu. const puppeteer = require('puppeteer'); (async ...

Tips for querying orchestrate.io

Recently, I found myself in need of a user-friendly database for a small highscore system in my game development projects using JavaScript. Through the Github student developer pack, I came across Orchestrate.io. After discovering a suitable driver module ...

getting rid of the angular hash symbol and prefix from the anchor tag

I am having difficulty creating a direct anchor link to a website. Whenever I attempt to link to the ID using: where #20841 is my anchor tag. Angular interferes with the URL and changes it to: This functions properly in Chrome and Firefox, but i ...

Avoid using the Input formControlName in the Angular 6 form

Before submitting the form, I want to be able to retrieve the value of the input tag with formControlName. I have tried creating a method to accomplish this, but I am unable to access the current input value. When I removed the formControlName to exclude ...

Are you looking for a demonstration of "Creative Loading Effects" that triggers when the page is loaded?

I came across this demo for a preloader on my website called Creative Loading Effects, specifically the "3D Bar Bottom" effect, which I find very exciting. However, I noticed that it only loads when we press the button, and not automatically when the page ...

Tips on organizing a typescript object/StringMap in reverse order to prioritize the last element

I've just started working with TS/React in a .tsx file and I'm trying to add a key/value pair to a StringMap at the very first index. Below is the code snippet that: takes the StringMap 'stats' as input, iterates through each row, re ...

Is it possible for me to design a unique path without relying on redux?

I am working on a Loginscreen.js component import React, { Component } from 'react'; import Login from './Login'; class Loginscreen extends Component { constructor(props){ super(props); this.state={ username:'&apo ...

Utilizing BehaviourSubject for cross-component communication in Angular

My table is populated with data from a nodeJS API connected to methods inside my service. I attempted using a Behavior Subject in my service, initialized as undefined due to the backend data retrieval: Service: import { Injectable } from "@angular/core" ...

Immutable.Map<K, T> used as Object in Typescript

While refactoring some TypeScript code, I encountered an issue that has me feeling a bit stuck. I'm curious about how the "as" keyword converts a Map<number, Trip> into a "Trip" object in the code snippet below. If it's not doing that, the ...

Is it possible to specify broad keys of a defined object in TypeScript using TypeScript's typing system?

const obj: {[key: string]: string} = {foo: 'x', bar: 'y'}; type ObjType = keyof typeof obj; Is there a way to restrict ObjType to only accept values "foo" or "bar" without changing the type of obj? ...

What is causing this issue with the ajax call not functioning correctly?

$(document).ready(function(){ $('.clickthetext').click(function(){ $.post("submit.php", $("#formbox").serialize(), function(response) { $('#content').html(response); }); return false; }); ...

Interactive loadChild components

I've been attempting to dynamically import routes from a configuration file using the following code snippet: export function buildRoutes(options: any, router: Router, roles: string[]): Routes { const lazyRoutes: Routes = Object.keys(options) ...

TextGeometry failing to render

Currently experimenting with TextGeometry. Successfully implemented BoxGeometry, but encountering issues with TextGeometry. Experimenting with different material options like MeshNormalMeterial, however, still unable to resolve the issue var scene = new ...

React: Maximum call stack size exceeded error was caught as an uncaught RangeError

I've been experimenting with React and I've managed to get the functionality I want, but it's running very slow due to an infinite loop lurking somewhere. I suspect the issue lies within the component lifecycle methods, but I'm unsure h ...

AngularJS: The delay in updating variable bindings following a REST API call

When utilizing a REST service, I wanted to implement a variable to show whether the service is currently loading or not. Controller $scope.loading = true; $http.get('/Something'). success(function(data, status, headers, config) ...

Achieve uninterrupted deployment of node.js applications by utilizing naught for zero downtime implementation

Recently, I began utilizing naught for deploying my node.js applications (https://github.com/andrewrk/naught). In my Ubuntu Server, I have a directory that contains my node.js (express) app. To deploy it, I used the command "naught start app.js" from tha ...