Tips for optimizing the functionality of the Angular search filter

When I type a search string in the column "Failure signature" in my code, it doesn't seem to work. The data is not filtered based on the search string provided, and an error is thrown. I have identified the line where the error occurs.

I have created a stackblitz link to reproduce the error. Interestingly, it works with dummy data, but when I switch to a backend URL to fetch data from the database, I encounter this error.

Here is the stackblitz link with the complete code: https://stackblitz.com/edit/angular-uxnrrr?file=src/app/failure-signature/failure-signature.component.html

failure-signature.component.html

<html ng-app="failure-signature">
  <h1>Root cause analysis Dashboard</h1>
  <nav class="navbar">
    <input
      class="form-control"
      type="text"
      name="Failure_signature"
      [(ngModel)]="Failure_signature"
      (ngModelChange)="Search($event)"
      placeholder="Search for failure signature...."
    />
  </nav>
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>commit</th>
        <th>gerrit</th>
        <th>failure_signature</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let cm of wifi_gerrit_commit_messages?.posts">
        <td>{{cm.commit_id}}</td>
        <td>{{cm.gerrit}}</td>
        <td>{{cm.Failure_signature}}</td>
      </tr>
    </tbody>
  </table>
</html>

failure-signature.component.ts

import { Component, OnInit, Injectable, ViewChild } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { DomSanitizer } from '@angular/platform-browser';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { enableProdMode } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { wifi_gerrit_commit_messages } from '../_model/wifi_gerrit_commit_messages';
import { FailureSignatureService } from './failure-signature-service';
import { RESOURCE_CACHE_PROVIDER } from '@angular/platform-browser-dynamic';

@Component({
  selector: 'app-failure-signature',
  templateUrl: './failure-signature.component.html',
  styleUrls: ['./failure-signature.component.css'],
  animations: [
    trigger('detailExpand', [
      state('collapsed', style({ height: '0px', minHeight: '0' })),
      state('expanded', style({ height: '*' })),
      transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')),
    ]),
  ],
})
export class FailureSignatureComponent {
  wifi_gerrit_commit_messages: wifi_gerrit_commit_messages[] = [];
  Failure_signature: any;
  constructor(public fss: FailureSignatureService) {}
  ngOnInit(): void {
    this.fss.get_wifi_gerrit_commit_messages().subscribe((Response) => {
      this.wifi_gerrit_commit_messages = Response;
    });
  }

  Search(value: string) {
    if (value == '') {
      this.ngOnInit();
    } else {
      this.wifi_gerrit_commit_messages = this.wifi_gerrit_commit_messages.filter((res) => {
        return res.Failure_signature.toLocaleLowerCase().match(this.Failure_signature.toLocaleLowerCase());
      });
    }
  }
}
Error Line:-

  this.wifi_gerrit_commit_messages = this.wifi_gerrit_commit_messages.filter(res => {
    return res.Failure_signature.toLocaleLowerCase().match(this.Failure_signature.toLocaleLowerCase());

ERROR:-

   at FailureSignatureComponent.push../src/app/failure-signature/failure-signature.component.ts.FailureSignatureComponent.Search (failure-signature.component.ts:50)
    at Object.eval [as handleEvent] (FailureSignatureComponent.ngfactory.js:62)
    at Object.handleEvent (core.js:27341)
    at Object.handleEvent (core.js:27886)
    at dispatchEvent (core.js:18085)
    at core.js:19288
    at SafeSubscriber.schedulerFn [as _next] (core.js:22113)
    at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:194)
    at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:132)
    at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:76)

UPDATED ERROR:-

ERROR TypeError: Cannot read properties of undefined (reading 'toLocaleLowerCase')
    at failure-signature.component.ts:77
    at Array.filter (<anonymous>)
    at SearchPipe.push../src/app/failure-signature/failure-signature.component.ts.SearchPipe.transform (failure-signature.component.ts:71)
    at checkAndUpdatePureExpressionInline (core.js:27032)
    at checkAndUpdateNodeInline (core.js:27601)
    at checkAndUpdateNode (core.js:27559)
    at prodCheckAndUpdateNode (core.js:28100)
    at Object.eval [as updateDirectives] (FailureSignatureComponent.ngfactory.js:89)
    at Object.updateDirectives (core.js:27888)
    at checkAndUpdateView (core.js:27541)

Answer №1

  • Instead of altering wifi_gerrit_commit_messages directly in your component.ts file, have you thought about creating a new property for the filtered results?

  • It seems like you are filtering this.wifi_gerrit_commit_messages but then displaying

    wifi_gerrit_commit_messages?.posts
    (with posts field) using *ngFor. Is this really what you intended to do?

Answer №2

Check out this Demo One crucial aspect to consider is that when creating a filter with your original value, you risk losing data to other filters because you are altering the original data. If you prefer not to use a second variable, you can utilize a pipe to customize the display in the HTML without affecting the data.

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

@Pipe({
  name: 'search',
})
export class SearchPipe implements PipeTransform {
  transform(value: any[], param: string): any {
    return value.filter(
      (x) =>
        param == null ||
        param == '' ||
        x.commit_id.toLocaleLowerCase().includes(param.toLocaleLowerCase()) ||
        x.gerrit.toLocaleLowerCase().includes(param.toLocaleLowerCase()) ||
        x.Failure_signature.toLocaleLowerCase().includes(
          param.toLocaleLowerCase()
        )
    );
  }
}

Furthermore, make sure to

integrate it into your HTML like this

*ngFor="let cm of wifi_gerrit_commit_messages | search: Failure_signature"

Answer №3

Initially, it's not ideal to repeatedly call ngOnInit() for setting up initial data. It's better to use a separate method for this purpose instead of relying solely on Angular lifecycle hooks. Consider storing the initial data in a DataSource for reuse. Another issue lies in the search logic, particularly within the Search method where the else section needs attention. What happens if invalid or no-results characters are entered? The original data entries are essentially overwritten when the filter is applied, unless the user clears the input.

The error message you're encountering seems to be more related to data manipulation rather than the Angular search filter. The specific error points to an undefined property, Failure_signature, during runtime. Address this by refining your data manipulation approach to avoid undefined variables. Consider writing test cases to uncover any potential flaws in your code.

Answer №4

Consider updating the searchTerm undefined check within your Pipe's transform function

transform(gerrit_commit_logs: any[], searchTerm: string): any {
        return gerrit_commit_logs.filter(
          (log) =>
            !searchTerm ||
            log.commit_id
              ?.toLocaleLowerCase()
              .includes(searchTerm?.toLocaleLowerCase()) ||
            log.gerrit
              ?.toLocaleLowerCase()
              .includes(searchTerm.toLocaleLowerCase()) ||
            log.error_message?.toLocaleLowerCase().includes(
              searchTerm?.toLocaleLowerCase()
            )
        );
      }

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

Is there a way to simulate Pinia and vue-i18n simultaneously?

Exploring Vue 3's Composition API with a twist: The store.ts file import { ref, Ref } from 'vue'; import { defineStore } from 'pinia'; export const useStore = defineStore('store', () => { const isLoading: Ref<bo ...

Angular Paginated Table with Sort and Filter Functionality

I am just beginning to explore Angular and have covered the basics. I'm looking to develop a Table that will retrieve data from the server for loading. What approach would be best? I need to pull data from the server based on the number of r ...

Having issues with the jquery append function not cooperating with the <ngx dropzone> component

I am trying to use the jQuery .append function, but it doesn't seem to be working for me. Is there a solution to this issue? <ngx-dropzone [showPreviews]="true" #dropzone [showPreviews]="true" [preserveFiles]="false" [accept]="'image/png, ...

Sporadic UnhandledPromiseRejectionWarning surfacing while utilizing sinon

Upon inspection, it appears that the objects failApiClient and explicitFailApiClient should be of the same type. When logging them, they seem to have identical outputs: console.log(failApiClient) // { getObjects: [Function: getObjects] } console.log(expli ...

Unusual problem with accessing Object values in vscode using typescript

When attempting to write Object.values in TypeScript, I encounter a visual error (although it compiles without issues). https://example.com/image1.png I have tried searching online and restarting vscode, and here is my current tsconfig.json. https://exa ...

Error Message: Unable to Load User Profile Pictures from Microsoft Graph

Currently, I am developing an application that makes requests for user profile photos from Microsoft Graph. The process seems to be working smoothly as the request returns a 200 status code and a significant amount of data is retrieved. However, when I att ...

I'm having trouble accessing the Angular application that is running inside a Docker container

I'm completely new to Docker, so please be patient with me. Here is my Dockerfile: FROM node:alpine WORKDIR '/app' COPY ./package.json . EXPOSE 4200 RUN npm i COPY . . CMD ["npm","start"] These are the commands I used: docker build -t an ...

Encountering a Template Parse Error after running the ng build --prod command

As a newcomer to Angular, I have successfully created a small application that requires a sortable table. Everything works well in Angular-cli development server during development mode (using ng serve). I've experimented with implementing the table ...

The color rendering of objects in the b3dm file is not displayed correctly by three.js

Currently, I am working on converting a file with a .b3dm extension to a .glft and then displaying it by loading it in three.js. For guidance, I am referring mainly to an interesting article. However, I seem to be facing an issue where the object is only ...

Attempting to revert the imported module back to its initial/default mock configuration

When working on my test file, I utilize a folder named mocks which contains various exported functions. Most of the time, I rely on the mocks folder to perform all necessary tasks. However, there is one scenario where I need to adjust the return value to a ...

Personalized prefix for Angular and WebStorm components

After starting a project in Angular with Visual Studio Code a few months ago, I decided to switch to WebStorm and upgraded the project to Angular 4.0 today. Although my project is running smoothly without any errors, I encountered an issue in WebStorm: ...

Obtain both the key and value from an Object using Angular 2 or later

I have a unique Object structure that looks like this: myCustomComponent.ts this.customDetails = this.newParameter.details; //the custom object details are: //{0: "uniqueInfo", // 5: "differentInfo"} The information stored in my ...

Implementing Custom Font Awesome Icons in Your Angular Project

I recently upgraded to a fontawesome subscription with a paid plan and have successfully created some custom icons. Now, I'm looking to integrate these icons into my angular app. Here are the dependencies listed in my package.json file: "@fortawe ...

Error in Angular: A ReferenceError has occurred stating that the bootstrap is not defined

I'm having trouble understanding why the error persists even though I've declared Bootstrap and confirmed it's defined when debugging. Does anyone have any insights on why this might be happening? Could it be related to Bootstrap? Here is t ...

Can you provide some instances of attribute directives?

I'm struggling to understand when it's best to implement an attribute directive, know when an attribute directive is necessary, utilize input and output properties Why should I use an attribute directive? I often find myself combining all l ...

An issue has been detected in the @angular/material/autocomplete/typings/autocomplete-origin.d.ts file: The type 'ElementRef' is not declared as a generic type

Recently, I downloaded an Angular template that utilizes the Angular Material library. While trying to run this template on my local machine, I successfully executed the npm install command. However, when attempting to run ng serve, I encountered several w ...

Is there a way to convert const files without using TranslocoService for importing?

Introduction Greetings! I am currently working on an Angular+Ionic project and utilizing Transloco for text translation. The issue at hand I have a constants file with strings that need to be translated, but I am facing a challenge in figuring out how to ...

The Gatsby + Typescript project is reporting that the module with the name "*.module.scss" does not have any exported members

I've recently gone through Gatsby's demo project in their documentation (which is long overdue for an update). I've carefully followed the instructions provided here: I've included an index.d.ts file in the /src directory of my project ...

What are the steps to integrate webpack with .NET 6?

Struggling to incorporate webpack into .NET 6 razor pages. The existing documentation online only adds to my confusion. Here is a snippet from my file1.ts: export function CCC(): string { return "AAAAAA"; } And here is another snippet from ...

Is there a way to access the callback function's arguments and its return value from outside the function?

Is it possible to access both the callback function argument and the return value of a function that takes a callback function as an argument, outside of the function? Consider the following example with a function called func_a. function func_a(callback: ...