Finding it frustrating that filtering doesn't work properly in the PrimeNG table component within Angular?

My current objective is to filter via Instances, and I have implemented the following code: Within my component.ts file:

import { Component, OnInit } from "@angular/core";
import { AlertingService } from "src/app/services/alerting.service";
import { AlertingDB } from "src/app/models/alerting-db";
import { DatePipe } from "@angular/common";
import { MessageService } from "primeng/api";

@Component({
  selector: "app-alerts-history",
  templateUrl: "./alerts-history.component.html",
  styleUrls: ["./alerts-history.component.css"]
})
export class AlertsHistoryComponent implements OnInit {
  AlertsHistory: AlertingDB;
  cols: string[];

  constructor(
    private alertingService: AlertingService,
    public datepipe: DatePipe,
    private messageService: MessageService
  ) {
    this.cols = [
      "Name",
      "Instance",
      "Severity",
      "Summary",
      "State",
      "Active Date"
    ];
  }

  ngOnInit() {
    this.alertingService.getAllAlertsFromDB().subscribe(res => {
      this.AlertsHistory = res;
    });
  }

  deleteHistory() {
    this.alertingService.deleteAllAlertsFromDB().subscribe(async result => {
      this.messageService.add({
        severity: "info",
        summary: "Success",
        detail: `History Cleared`,
        sticky: true
      });
      this.AlertsHistory = await this.alertingService
        .getAllAlertsFromDB()
        .toPromise();
    });
  }
}

In the corresponding component.HTML file:

<button
  pButton
  type="button"
  label="Clear History"
  class="ui-button-danger"
  style="margin-bottom: 15px;margin-top: 15px;"
  (click)="deleteHistory()"
></button>
<div>
  <p-table
    autoLayout="true"
    ng-style="overflow: auto;"
    #dt
    [columns]="cols"
    [value]="AlertsHistory"
    [paginator]="true"
    [rows]="15"
  >
    <ng-template pTemplate="header" let-columns>
      <tr>
        <th *ngFor="let col of columns" [pSortableColumn]="col">
          {{ col }}
          <p-sortIcon
            [field]="col"
            ariaLabel="Activate to sort"
            ariaLabelDesc="Activate to sort in descending order"
            ariaLabelAsc="Activate to sort in ascending order"
          >
          </p-sortIcon>
        </th>
      </tr>
      <tr>
        <th *ngFor="let col of columns" [ngSwitch]="col">
          <input
            *ngSwitchCase="'Instance'"
            pInputText
            type="text"
            (input)="dt.filter($event.target.value, col, col.filterMatchMode)"
          />
        </th>
      </tr>
    </ng-template>
    <ng-template pTemplate="body" let-alert>
      <tr [pSelectableRow]="alert">
        <td>{{ alert.name }}</td>
        <td>{{ alert.instance }}</td>
        <td>{{ alert.severity }}</td>
        <td>{{ alert.summary }}</td>
        <td>{{ alert.state }}</td>
        <td>{{ alert.activeAt | date: "medium" }}</td>
      </tr>
    </ng-template>
  </p-table>
</div>

The associated component.model.ts file contains:

export class AlertingDB {
  id: number;
  name: string;
  instance: string;
  severity: string;
  summary: string;
  state: string;
  activeAt: string;
}

Finally, within my component.service.ts file:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
import { Response } from "@angular/http";
import { environment } from "src/environments/environment";
import { Alerting } from "../models/alerting";
import { AlertingDB } from "../models/alerting-db";

@Injectable({
  providedIn: "root"
})
export class AlertingService {
  private AlertingUrl = environment.API_URL + "Alerting"; // URL to web api

  constructor(private http: HttpClient) {}

  getAllAlertsFromDB(): Observable<AlertingDB> {
    return this.http.get(this.AlertingUrl + "/getAll").pipe(
      map((response: AlertingDB) => {
        return <AlertingDB>response;
      })
    );
  }
  deleteAllAlertsFromDB(): Observable<AlertingDB> {
    return this.http.delete<AlertingDB>(this.AlertingUrl);
  }
}

Despite all functions working correctly, there seems to be an issue with the filtering functionality. Although no errors are shown in the console, the filter function does not provide the expected results. For example: When fetching all instances, everything appears as expected:

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

However, when attempting to filter the instances, it returns 0 items:

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

If anyone can offer assistance on resolving this filtering problem, it would be greatly appreciated. Thank you! :)

Answer №1

You need to apply a filter to your column based on the value of col.filterMatchMode

The problem lies in your component where cols is an array of strings. This causes col.filterMatchMode to always be undefined in the template.

To fix this, you have two options:

<input
  *ngSwitchCase="'Instance'"
  pInputText
  type="text"
  (input)="dt.filter($event.target.value, col, 'in')"
 />

Alternatively, update your cols array so that it includes properties like filterMatchMode and name:

this.cols = [
  {name: "Name"},
  {name: "Instance", filterMatchMode: 'in'},
  {name: "Severity"},
  {name: "Summary"},
  {name: "State"},
  {name: "Active Date"}
];

Then modify your template as follows:

<ng-template pTemplate="header" let-columns>
  <tr>
    <th *ngFor="let col of columns" [pSortableColumn]="col.name">
      {{ col.name }}
      <p-sortIcon
        [field]="col.name"
        ariaLabel="Activate to sort"
        ariaLabelDesc="Activate to sort in descending order"
        ariaLabelAsc="Activate to sort in ascending order"
      >
      </p-sortIcon>
    </th>
  </tr>
  <tr>
    <th *ngFor="let col of columns" [ngSwitch]="col.name">
      <input
        *ngSwitchCase="'Instance'"
        pInputText
        type="text"
        (input)="dt.filter($event.target.value, col.name, col.filterMatchMode)"
      />
    </th>
  </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

Generate a compressed file in RAM and then save it to Amazon S3

I'm currently working on a project where I need to compress text data into a zip file in memory using TypeScript and then upload it to an AWS S3 bucket. The input data is in plain text CSV format. However, I seem to be encountering an issue where the ...

Using Material-UI with TypeScript

Attempting to integrate TypeScript/React with Material UI has been quite the challenge for me so far. Here is my index.tsx file: declare function require(p: string): any; var injectTapEventPlugin = require("react-tap-event-plugin"); injectTapEventPlugin( ...

Is it possible for Angular 7 to disconnect from the internet?

I am looking to disable all buttons, clicks, and hyperlinks while displaying a backdrop with the message "GO ONLINE". It may come off as rude, but it is necessary. AppComponent (TS): The connectionMonitor can be used to monitor network connectivity. pr ...

Arranging Data in Arrays using Angular 4 GroupBy Feature

I'm working with an array structured like this: var data = [ { student: "sam", English: 80, Std: 8 }, { student: "sam", Maths: 80, Std: 8 }, { student: "john", English: 80, Std: 8 }, { student: "j ...

The powerful combination of Angular 6, NodeJS, and MongoDB creates a

Hi there. I've been searching around but couldn't find a solution to my problem. There are two similar unanswered questions. I'm new here, so any help with my final project would be greatly appreciated. After running ngForm, I encountered a ...

An effective method for normalizing URLs within an Angular application to ensure proper resolution when the app is either self-hosted or integrated

When we mention "integrated" in this context, we are referring to an angular app that is called from a specific path within another web app. On the other hand, "self hosted" means running the app from a tool like VS Code using the ng serve --open command, ...

Identifying whether an Angular component has been loaded through a template or a route: Ways to distinguish

How can I determine how an Angular component was loaded? I have a component that can be accessed through a route or loaded within another component's template, and I want to be able to identify the loading method for the purpose of animations. ...

Encountered a problem while attempting to build with ng build --prod. No issues when using ng serve or excluding

My project was working smoothly with ng build --prod until I decided to update the TypeScript version from 2.72 to 2.92 in my package.json file. Now, after the update, an error message pops up: ERROR in Cannot read property 'Symbol(Symbol.iterator ...

Designing a unique and customized theme for Angular 4

Exploring the world of Angular 4 and Angular Material is an exciting journey for me. Currently, I am delving into the creation of a custom theme in Angular 4. In order to achieve this, we make use of variables to assign colors to primary, accent, and warn ...

"When attempting to render a Node inside the render() method in React, the error message 'Objects are not valid as a React child' is

On my webpage, I have managed to display the following: export class OverworldComponent extends React.Component<OverworldComponentProps, {}> { render() { return <b>Hello, world!</b> } } However, instead of showing Hello, ...

What is the proper type declaration for incoming data from the backend in my TypeScript code when using axios?

In the TypeScript code snippet provided, the type for 'e' (used in the function for form submission) has been figured out. However, a question arises if this type declaration is correct. Additionally, in the catch block, the type "any" is used fo ...

Establishing a response header in conjunction with a specified string

I'm facing an issue while attempting to include a token in the headers of an HTTP request from backend to frontend, along with sending a custom string. Despite my efforts, I am encountering a problem where the token appears as null on the client-side. ...

What is the best way to transfer authentication details from an Angular2 frontend to a Spring backend using Basic-Authentication with Spring Security?

Working on a project that combines spring for the backend and angular2 for the frontend. The backend is secured using Spring Security with a default login form. Need to implement client-side log in, but encountering browser console errors when passing cred ...

Generating Components Dynamically in Angular 4 Based on User-Defined Input

I am interested in developing an innovative App using Angular 4 that enables the creation of components from various storage sources such as database, URLs, and server-stored files. The main objective is to allow users to design their own components for pe ...

Issue with ngb-carousel not properly loading upon page refresh within an Angular project

I have integrated ngb-carousel into my Angular application for a basic website. Overall, everything is functioning correctly, but I have noticed that when I refresh the page, the carousel's image takes longer to load compared to the indicators and arr ...

Angular 2/4: Struggling to refresh child component's view

I need assistance with updating the value of "str" in the child component's view from the parent component. I want to do this by calling the "change()" function in the child component. Here is my code: import { Component } from '@angular/core&ap ...

Using Angular's ngStyle directive to apply multiple styles

Currently, I am developing a basic animation library that allows users to customize components using property binding. Up to this point, I have been applying their selections like so: <div [style.background]="color" [style.width.px]="width" [style.heig ...

Angular TypeScript error: "Cannot assign type '(string | undefined)[]' to type 'string[]'."

I've been following the instructions in the book Pro Angular 9 written by Adam Freeman. I encountered an error on line 8: private categories: string[] = []; The error message reads: Error: src/app/model/product.repository.ts:13:7 - error TS2322: Type ...

Ways to conceal table rows depending on their content

I am currently developing a project using Angular 2. One of the features includes a summary section that consolidates all the data from other sections. The summary is presented in a table format, with each row displaying the field name in the first colum ...

Components on different routes are not being triggered by the `BehaviourSubject` subscription

In my current project, I am working on transferring data between components using a subject. I have created a service for this purpose, and the two components involved are imagescust and imagesipa. The data is being passed from the imagesipa component and ...