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

Converting JSON data into an Angular object

I'm struggling to map the JSON data below to an Angular 7 object: [ { "id": "123456", "general": { "number": "123", "name": "my name 1", "description": "My description with <li> html tags ...

Creating a shimmering glow for a dynamic AJAX div block in real-time

I created an Ajax code that retrieves results from a txt file in real time, which are then automatically displayed in a div block using the following lines: if (xmlhttp.responseText != "") { InnerHTMLText = xmlhttp.responseText + document.getElementBy ...

Why is only the peak of the wave visible? I am eager to showcase the full extent of its beauty

Having an issue with the appearance of a superposed wave using threejs. When displayed, the wave made from plane material only shows the upper half, but when turned upside down using mouse dragging, it appears correctly. // Turn the wave plane upside down ...

What is the best way to ensure a texture is always facing the camera?

Latest Update: We have created a new demo to showcase the desired outcome. The demo includes an invisible skydome, a cubecamera, and an environment map. However, it is important to note that these techniques should not be utilized for the reasons previous ...

What is the best way to populate MongoDB with information retrieved from an external API?

Recently, I've been diving into the world of NodeJS with mongoose & mLab. As someone new to these technologies, I'm slowly piecing together my model. Here's what it looks like for now, with plans to expand the schema down the road. cons ...

How should you proceed when npm install cannot locate a specific dependency, even though you can easily download it manually?

Currently, I am faced with a dilemma while attempting to execute a JavaScript file that is accompanied by a package.json file. The issue arises during the npm install command in the folder as it fails to locate one of the dependencies. To address this pro ...

Having difficulty formatting text alignment using CSS

Is there a way to maintain the alignment of text in the output of the 'About' section even when the content changes dynamically? I want the new line to appear just below 'Lorem', but currently, it shifts below the colon(:). Since the le ...

Retrieving the necessary data from my object to perform a sum calculation in angular

Having trouble retrieving an attribute from an array in my code. In my .ts file, I am fetching data from my backend endpoint like this: export class PostFeedComponent implements OnInit { data: any = {}; constructor(private http: HttpClient) { t ...

Problem with $http.post() in Angular where Codeigniter is not able to receive data

I'm facing a peculiar issue with Codeigniter and Angular. My approach was to configure the controller in the following way: index is a simple Angular page with just one app and one controller get retrieves data from the database set saves data sent u ...

Passing a PHP array to a JavaScript function using a button click event in an HTML form

It seems there was some confusion in my approach. I'm working with a datatable that has an edit button at the end. Clicking on this button opens a modal, and I want to pass the data from the table to the modal. While I can send it as a single variabl ...

Guide to assigning a value to a model in AngularJS by utilizing a select input with an array of objects

I'm new to AngularJS and I've encountered a challenge that requires an elegant solution. My application receives a list from the server, which is used as the data source for the select tag's options. Let's assume this list represents a ...

Update information without the need for an xhr request in the back-end using jQuery

To keep notification updated with any changes in the database without causing a slowdown to the website, I implemented the following solution: HTML Code: <div id="myid">{{ $db_data }}</div> Back-end Request (utilizing Laravel): $db_data = A ...

Integrate ruby code within a javascript string

I am looking to insert tfx-<%= @doc.doc[:b].metadata['filename']} %> into a JavaScript string called 'url' url = "<%= @document.doc[:a].url(response_content_disposition: ContentDisposition.attachment( [INSERT HERE] )) %>"; ...

Understanding the application of JSON data can be simplified by following these

I am looking to manipulate dates by either adding or subtracting them, but I am unsure of how to extract the dates from the other data present. var fetch = require('node-fetch'); fetch('https://api.nasa.gov/planetary/earth/assets?lon=100.7 ...

Stranger things happening when incorporating a generator function in React

Here's a simplified version of my component. It includes a generator function that cycles through values. const App = () => { const [state, setState] = useState("1") function* stateSwitch () { while (true){ yield "2" yield "3" ...

What is the best way to organize notifications by dates in a React application?

I'm currently working on a notifications component where I need to sort notifications by dates and then display them. Although I attempted the following code, it didn't work as intended: const result = notifications.notificationRows.sort((a, b) ...

What is the best way to display only the current != wanted lines when using "npm outdated"?

Whenever I input npm outdated, it shows a similar output like this: Package Current Wanted Latest Location columnify 1.1.0 1.1.0 1.2.1 /usr/local/lib > npm > columnify cmd-shim 1.1.2 1.1.2 2.0.0 /usr/local/lib & ...

Sharing data between two PHP pages via an AJAX request

On my webpage, specifically on page 1.php, I am saving a variable to an input field text. Name:abc Done. After clicking the 'done' button, the name abc is sent to another page called 2.php via an Ajax request. In 2.php, I am storing the value ...

Enable the execution of a function only once a specific period of time has elapsed

Here's the scenario I'm dealing with: In a fun group chat with my friends, I created a giphy bot that responds to /giphy [terms] messages by posting the top result for those terms. However, my friends started abusing it by spamming the chat. To ...

Modifying the disabled attribute of an input tag upon button click in Angular 2

I am currently working on a function in Angular 2 where I want to toggle the disabled attribute of an input tag upon button click. Right now, I can disable it once but I am looking to make it switch back and forth dynamically. Below is the HTML template c ...