Filtering based on the boolean value of a checkbox in Angular

I'm struggling to implement a boolean filter for my search results, separating users with financial debt from those without. I need some guidance on how to achieve this.

Data Filter

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(tenants:Tenant[], searchTerm : string): Tenant[] {
    if(!tenants || !searchTerm){
      return tenants;
    }
    return tenants.filter(tenant => 
      tenant.name.toLocaleLowerCase().indexOf(searchTerm.toLocaleLowerCase()) !== -1);
  }
}

https://i.sstatic.net/QGgvG.png

ngOnInit() {
  this.userService.getAllTenants().subscribe((data:Tenant[])=>{
    this.lstTenants = data.Tenants;
    console.log("Tenants:", this.lstTenants)
  })
}

<div class="small-container">
        <h1>Tenants</h1>
        <button class="add" [routerLink]="['/add']">Add New Tenant</button>
        <input type="search" placeholder="Search Tenants" [(ngModel)]="searchTerm" [ngModelOptions]="{standalone: true}">
        <form>
            <div class="form-group">
                <label>
            <span>Show Financial Debt Only</span> 
            <input class="form-control mb-2" type="checkbox" [(ngModel)]="hasFinanacialDebt"  [ngModelOptions]="{standalone: true}">
        </label>
            </div>
            <div class="form-group">
                <label>
            <span>Show Non-Financial Debt Only</span> 
            <input class="form-control mb-2" type="checkbox" [(ngModel)]="hasntFinanacialDebt"  [ngModelOptions]="{standalone: true}">
        </label>
            </div>
        </form>

                <tr *ngFor="let tenant of lstTenants | filter : searchTerm">
                    <td>{{tenant.name}}</td>
                    <td>{{tenant.phoneNumber}}</td>
                    <td>{{tenant.address}}</td>
                    <td>{{tenant.financialDebt}}</td>
                    </tr>

Data Model Interface

export class Tenant {
    name:String;
    phoneNumber:Number
    address:String;
    financialDebt:Boolean
}

Answer №1

Consider using:

pipe

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "filter"
})
export class FilterPipe implements PipeTransform {
  transform(data: any, key: string, financial: any, non_financial: any): any {
    if (!data || data.length === 0) {
      return [];
    }
    console.log(key,financial,non_financial)

    return data.filter(item => (item[key] == financial || item[key] == non_financial));
  }
}

And ensure your *ngFor is structured like this

*ngFor="let user of lstTenants | filter:'financialDebt':financial:nonFinancial"

app.component.html

<div class="container" style="margin-top: 40px;">
    <input type="checkbox" id="financial" (change)="setFinancial($event)"/>
    <label style="margin-left: 10px;" >Financial Dept Users</label>
    <hr>
    <input type="checkbox" id="not_financial" (change)="setFinancial($event)"/>
    <label style="margin-left: 10px;">Not Financial Dept Users</label>
    <hr>
    <table class="table">
        <thead>
            <tr>
                <th>Address</th>
                <th>Created At</th>
                <th>Financial Debt</th>
            </tr>
        </thead>
        <tr *ngFor="let user of lstTenants | filter:'financialDebt':financial:nonFinancial">
            <td>{{user.address}}</td>
            <td>{{user.createdAt}}</td>
            <td>{{user.financialDebt}}</td>
        </tr>
    </table>
</div>

app.component.ts

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  financial = true;
  nonFinancial = false;
  lstTenants = [
    { address: "Adam", createdAt: "Passed", financialDebt: true },
    { address: "Adam", createdAt: "Passed", financialDebt: false },
    { address: "Adam", createdAt: "Passed", financialDebt: true },
    { address: "Adam", createdAt: "Passed", financialDebt: false },
    { address: "Adam", createdAt: "Passed", financialDebt: true },
    { address: "Adam", createdAt: "Passed", financialDebt: false },
    { address: "Adam", createdAt: "Passed", financialDebt: true },
    { address: "Adam", createdAt: "Passed", financialDebt: false },
    { address: "Adam", createdAt: "Passed", financialDebt: true },
    { address: "Adam", createdAt: "Passed", financialDebt: false },
    { address: "Adam", createdAt: "Passed", financialDebt: true },
    { address: "Adam", createdAt: "Passed", financialDebt: false }
  ];

  setFinancial(evt) {
    if (evt.target.id == "financial") this.nonFinancial = evt.target.checked;
    else this.financial = !evt.target.checked;
  }
}

View the stackblitz demo here:

https://stackblitz.com/edit/angular-array-pipes-j23kb1?file=src/app/app.component.html

May this guide you on your journey :)

Answer №2

Your current pipe implementation only accepts the searchTerm as a parameter. Consider allowing multiple parameters or passing an object that encapsulates all your filters.

Here is an example with multiple parameters:

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {
  transform(tenants:Tenant[], searchTerm: string, hasFinancialDebt: boolean, hasntFinancialDebt: boolean): Tenant[] {
    if(!tenants){
      return tenants;
    }
    return tenants.filter(tenant =>
      (!searchTerm || tenant.name.toLocaleLowerCase().indexOf(searchTerm.toLocaleLowerCase()) !== -1) && 
      (!hasFinancialDebt || tenant.financialDebt) && 
      (!hasntFinancialDebt|| !tenant.financialDebt));
  }
}
<tr *ngFor="let tenant of lstTenants | search:searchTerm:hasFinanacialDebt:hasntFinanacialDebt">
    <td>{{tenant.name}}</td>
    <td>{{tenant.phoneNumber}}</td>
    <td>{{tenant.address}}</td>
    <td>{{tenant.financialDebt}}</td>
</tr>

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

What could be preventing my state from changing to false when I click the close button on the menu?

Despite initializing my state to false, the problem arises when I open and close my menu. The state never actually becomes false, causing the closing animation of the NavBar to not run as expected. The component: import CloseButton from "./CloseButto ...

Learn the steps to translate conditional string interpolation with NGX-translate

My application has a toggle button that dynamically changes the label to either 'Enabled' or 'Disabled'. I am attempting to utilize ngx-translate for translation, but I am encountering difficulties in achieving this. Can anyone provide ...

What is the reason behind the varying display of values?

When trying to set a value using the input tag, I encountered an issue. For example, if I type 1000.0009 into the input text, the valid value should be 1000.0001. However, the value displayed in the input tag is incorrect, while the value outside the tag i ...

What could be causing the conditional div to malfunction in Angular?

There are three conditional div elements on a page, each meant to be displayed based on specific conditions. <div *ngIf="isAvailable=='true'"> <form> <div class="form-group"> <label for ...

What are the steps to save information to Firebase's Realtime Database?

Currently, I am facing an issue where user location data is not being written into our Firebase Realtime Database even though the console confirms that the data is fetched correctly every 2 seconds. I am seeking assistance on how to resolve this problem. ...

Is it possible to stop Angular requests from being made within dynamic innerhtml?

I have a particular element in my code that looks like this: <div [innerHtml]="htmlContent | sanitiseHtml"></div> The sanitiseHtml pipe is used to sanitize the HTML content. Unfortunately, when the htmlContent includes relative images, these ...

Issues with naming in Gulp, Angular2 Final, and Visual Studio: "Cannot find name" and "Duplicate identifier" errors

Recently, I updated my project to utilize the final release of Angular 2 and also upgraded Visual Studio to use TypeScript 2.0.3 from the Tool -> Extensions and Updates manager. I compile my TypeScript using Gulp, and it compiles without any errors. Ho ...

options argument containing a keyof this

When defining a method type signature, it is possible to use keyof this to restrict an argument to the string name of a valid key of the class. However, using this approach does not work when the method accepts options-style arguments instead of positional ...

I'm curious about how to implement textarea functionality within Angular for modeling purposes

I have a desire to utilize the model and transmit it to the server. One instance of this is sending comments. comment.model.ts export interface Comment { article_no: number; username: string; nickname: string; creatat: Date; content: string; } ...

Exploring the Impact of 2 HostBindings on Class Generation from Inputs in Angular 4

I'm struggling with the code in my component, which looks like this: @Component({ selector: "home", templateUrl: "./home.html" }) export class Home { constructor() {} @HostBinding("class") @Input() public type: string = "alert" @HostBindi ...

Assistance required for setting a value in a mat-select using Angular

Could really use some assistance resolving the issue with mat-select I'm aiming to establish the initial values by utilizing the following code snippet: orders: Order[] = [{"dish":"steak-0"},{"dish":"tacos-2" ...

Phaser.js troubleshooting: Overcoming TypeScript errors

I encountered two persistent errors that I have been unable to resolve. While the application runs smoothly in Vite, it fails to transpile due to the mentioned errors outlined below: import Phaser from "phaser"; export default class GameScene ex ...

Having trouble with the sx selector not functioning properly with the Material UI DateTimePicker component

I'm currently working with a DateTimePicker component and I want to customize the color of all the days in the calendar to match the theme color: <DateTimePicker sx={{ "input": { color: "primary.main&quo ...

Discovering a method to recover information obtained through intercepting an observable

I am currently working on an Angular 6 cli application where a component utilizes a service to fetch data. As part of my project, I am incorporating an ngrx store into the application. I am considering abstracting the interactions with the store within the ...

Tips for implementing self-managed state in Vue.js data object

My approach in organizing my Vue application involves using classes to encapsulate data, manage their own state (edited, deleted, etc), and synchronize with the back-end system. However, this method seems to conflict with Vue in some respects. To illustra ...

Make sure to declare rest parameters first when using Typescript

I am dealing with a function that takes in multiple string arguments and one final argument of a complex type, which is called Expression. This particular code looks like this in JavaScript: function layerProp(...args) { const fields = args.slice(0, -1) ...

Center align the mat-expansion-panel material component in a vertical orientation

When working with the mat-expansion-panel component alongside a mat-accordion, I've encountered an issue where the items are not aligning vertically at the center/middle. I'm unsure of the proper method to achieve vertical alignment for the conte ...

Obtain the total number of requests submitted by the user within a 24-hour period

I have a POST request point in my API where I need to track and store all work journals made by a worker. export const registerPoint = async (req: Request, res: Response) => { const user = res.locals.decoded; const {id} = user; const point = new Point ...

Accessing unique identifiers from Firebase Database with AngularFire

My Firebase Database is structured as shown below: fire-demo-123 course 1 : "course1" 2 : "course2" 3 : "course3" -MzOn2s : "course4" I am currently using the following code to fetch the list component.t ...

Convert normal text to clickable links in chat messages within an angular application automatically

I'm working on incorporating a chat feature into an Angular application. One of my goals is to automatically detect URLs in the text that users enter and display them as clickable links when sent. So far, I have attempted to achieve this by using: & ...