Steps for incorporating a filter feature in an Angular Material table

.HTML:

Can someone assist me with implementing a filter in this component? I tried using it with the expansion table, but unfortunately, the filter is not working as expected.

    <mat-dialog-content style="width: 63rem; overflow: initial;">       
      <div class="searchField">
        <mat-form-field appearance="standard">
          <mat-label>Filter</mat-label>
          <input matInput (keyup)="applyFilter($event)" placeholder="Ex. Tele" #input>
        </mat-form-field>
      </div>  
     
    </mat-dialog-content>

.TS:

    getProductList() {
        this.commonservice.getProdList().subscribe((response: any) => {
          console.log('Response from API is ', response);
          if (response) {
            this.productInfo = response;
            this.dataSource = this.productInfo;
            console.log('Product Info ', this.productInfo);
          }
        }, (error) => {
          console.log('Error is ', error);
        });
      }

    applyFilter(event: Event) {
        const filterValue = (event.target as HTMLInputElement).value;
        this.dataSource.filter = filterValue.trim().toLocaleLowerCase();
        console.log('filtered data ', this.dataSource.filter);
      }

https://i.stack.imgur.com/7CfUK.png https://i.stack.imgur.com/5Avr0.png

Answer №1

If the dataSource is an array, you can use the filter method like this:

this.dataSource = this.dataSource.filter((data) => data === filterValue.trim().toLowerCase());

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

Error: Unable to assign value to the property 'address' as it is undefined in SafeSubscriber._next

Struggling to pass data to an array that is declared inside the component. Only the first index of the array is being returned, while the other elements are not. I've learned that the program works asynchronously and only retrieves the first index. S ...

Angular 6 Checkbox Selector - Filtering Made Easy

How can I filter a list of JSON objects (Products) by the 'category' variable using checkboxes? An example product object is shown below: { 'bikeId': 6, 'bikeName': 'Kids blue bike', 'bikeCode': ...

The state of dynamically created Angular components is not being preserved

My current task involves dynamically creating multiple components to be placed in a table. The code successfully achieves this objective, but the state seems to be getting jumbled up at the level of the dynamically generated components. When a component is ...

The mark-compacts were not efficient enough, they approached the heap limit and as a result, the allocation failed. The JavaScript

Currently working with Angular version 7.2 and encountering an issue when running ng serve: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory What does this error mean? How can it be resolved? The ...

Leveraging the power of Chart.js and Ng2-Chart within the Cumulocity platform

I'm currently in the process of developing an Angular application for the Cumulocity IoT platform and I wanted to incorporate custom bar charts using Chart.js. Initially, I faced some challenges with this setup but after some research, I came across n ...

Measuring Feedback: Utilizing Angular 4 to calculate review ratings

I'm facing a challenge while working on a review form using Firebase and Angular 4. The issue is with calculating the total length of added reviews and the sum of their ratings. Each time a new review is submitted, it gets pushed to a list of objects ...

Reactjs-ffsevents does not exist as a function

An error occurred: TypeError: fsevents is not a function. This issue is located in the FSEventsWatcher file at line 162. A new FSEventsWatcher was attempted to be created in jest-haste-map, triggering this error. The watcher creation process involved map ...

Challenge encountered with TypeScript integration in the controller

I am currently in the process of converting a website from VB to C# and incorporating TypeScript. I have successfully managed to send the data to the controller. However, instead of redirecting to the next page, the controller redirects back to the same pa ...

The iframe is not large enough to contain all the HTML content

I'm encountering a problem with a website I'm currently developing - specifically, I am struggling to embed an HTML document into an iframe in a manner that fills the entire page. Additionally, I am utilizing Angular to retrieve the HTML document ...

What causes Angular to consistently redirect to the homepage?

Whenever I attempt to access the '/' route, it consistently displays the static-root-component (the main page component). However, if I try to access the '/welcome' route, it immediately redirects back to '/' and loads the sta ...

New feature: Mat select placeholder color change without needing required field validation

When the page initially loads, all controls (such as city, state, etc.) have white text color as shown in Image 1. I want to change the text color to red for all controls upon loading the page, resulting in a look similar to the image below. In the sectio ...

The 'google.maps' namespace does not export the 'MouseEvent' member after installing @agm/core and @types/google

When attempting to install @agm/core and @types/google maps, I encountered the following errors: node_modules/@angular/google-maps/map-polyline/map-polyline.d.ts:42:45 - error TS2694: Namespace 'google.maps' does not have an exp ...

The art of neatly bundling a Typescript external module at the highest level

I'm currently working on a TypeScript NPM package, where I have organized all the classes and interfaces. However, upon review, it seems that my approach is repetitive and not very clean, especially with the empty class and interface extensions. I am ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

When utilizing Ionic with Angular, it is difficult to access the hardware back button on mobile devices that have buttons located within the display/screen

When trying to access the hardware back button in my app, I encountered an issue where I couldn't produce an alert message to the user before the app closed. After posting a question on Stack Overflow (link of the question) and receiving help from the ...

Unit testing for Angular service involving a mock Http GET request is essential for ensuring the

I am seeking guidance on how to test my service function that involves http get and post calls. I attempted to configure the spec file by creating an instance of the service, and also consulted several sources on creating a mockhttp service. However, I enc ...

Guide on displaying information on a pie chart in Angular 2 using ng2-charts

How can I display data on a pie chart like this? Like shown in the image below: <canvas baseChart class="pie" [data]="Data" [labels]="Labels" [colors]="Colors" [chartType]="pieChartType"> </canvas> public Labels:string[]=['F ...

I am interested in creating a class that will produce functions as its instances

Looking to create a TypeScript class with instances that act as functions? More specifically, each function in the class should return an HTMLelement. Here's an example of what I'm aiming for: function generateDiv() { const div = document.crea ...

Should the getDownloadURL() from Firebase Storage be regenerated every time, or can it be reused?

Should I store and reuse the URL received from angularfire2's getDownloadURL() in the database instead of calling getDownloadURL() every time I want to show an image from Firebase Storage? Whenever I use getDownloadURL() in my component, the images a ...

Using Jest: A guide to utilizing a mocked class instance

When working on my frontend React application, I decided to use the auth0-js library for authentication purposes. This library provides the WebAuth class which I utilize in my code by creating an instance like so: import { WebAuth } from 'auth0-js&ap ...