Angular: Refresh mat-table with updated data array after applying filter

I have implemented a filter function in my Angular project to display only specific data in a mat-table based on the filter criteria.

Within my mat-table, I am providing an array of objects to populate the table.

The filtering function I have created looks like this:

import {Component, ViewChild} from '@angular/core';
import {MatTable} from '@angular/material';

@ViewChild('TABLE') table: MatTable<any>;

dataSource: CandidateDataSource | null;

filterTableFunction(form) {

   let result = this.dataSource.data.filter(obj => {

        if (form.userValidation === true) {
            return obj.candidateState === 'userValidation';
        }

    });

    this.dataSource.filteredData = [...this.result];
    this.table.renderRows();

    console.log('The updated data source is:', this.dataSource.filteredData);
    console.log('The filtered result is:', result);
 }

While checking the console, I noticed that the new filtered array is accurate, but the table does not reflect these changes.

I attempted to make "result" a global variable, but unfortunately, it did not resolve the issue.

UPDATE:

The initial solution did not solve the problem as expected.

Updated code snippet:

// public
public result = [];

filterTableFunction(form) {

     console.log('#1', this.dataSource.data); //logs an array of objects

    this.result = this.dataSource.data.filter(obj => {

            if (form.userValidation === true) {
            return obj.candidateState === 'userValidation';
        }

   });

   console.log('#2' , this.result); // New array containing the objects with candidateState === 'userValidation'

    this.dataSource.data = [...this.result];

    this.table.renderRows();

   console.log('#3', this.dataSource.data) // Shows replaced array from above line with the correct result

 }

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

Answer №1

  1. result variable gets overwritten with previous values.
  2. Using the spread operator may not be necessary as this.dataSource.data is already an array.

Here is a suggested modification:

filterTableFunction(form) {
  const result = this.dataSource.data.filter(
    obj => { 
      if (form.userValidation === true) {
        return obj.candidateState === 'userValidation';
      }  
    }
  );

  this.table.renderRows();
}

If you want to extract an array of values from the candidateState key in the objects, you can use map().

// resultValues = ['userValidation', 'userValidation', 'userValidation', ...]
const resultValues = result.map(r => r.candidateState);

Check out a working example: Stackblitz

Answer №2

After consulting MichealID's response, I managed to come up with the following resolution:

Implementation of the filter function in component.ts:

public result = [];


async submitFilter(form) {

    this.result = this.dataSource.filteredData.filter(obj => {
        if (form.userValidation === true) {
            return obj.candidateState === 'userValidation';
        }

    });

    const resultValues = this.result.map(r => r.candidateState);

    this.dataSource.filter = resultValues[0];

    console.log(this.dataSource.filteredData);
}

In my datasource.ts file:

 // Private
 private _filterChange = new BehaviorSubject('');
 private _filteredDataChange = new BehaviorSubject('');

 constructor( private _candidateService: CandidateService){
    this.filteredData = this._candidateService.candidateData;
 }

// Filtered data
get filteredData(): any {
    return this._filteredDataChange.value;
}

set filteredData(value: any) {
    this._filteredDataChange.next(value);
}

// Filter
get filter(): string {
    return this._filterChange.value;
}

set filter(filter: string) {
    this._filterChange.next(filter);
}

filterData(data): any {
    if (!this.filter) {
        return data;
    }
    return FuseUtils.filterArrayByString(data, this.filter);
}

While I may be out of my depth with this approach, I resorted to a "hack" to extract the candidateState value from my array and use it for filtering. Although this solution may not be ideal as it limits me to filtering based on a single criteria, such as "candidateState," as opposed to multiple filters like "salary." Nevertheless, it serves its purpose for now by displaying objects with the specific value I desired. Special thanks to MichealID for the assistance.

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

The protractor tool is unable to recognize an Angular component when it is displayed on the page

I have implemented end-to-end (e2e) testing on my project, but I am facing issues that are causing my tests to fail. Below is a snippet of my app.po.ts file: import { browser, by, element } from 'protractor'; export class AppPage { public b ...

`Vanilla JavaScript AJAX request without using any external libraries or

Seeking advice on creating an ajax request function that is compatible across various browsers without relying on a javascript framework such as jQuery. Any ideas or suggestions are appreciated! ...

When I select a checkbox in Angular 2, the checkall function does not continue to mark the selected checkbox

How can I check if a checkbox is already marked when the selectAll method is applied, and then continue marking it instead of toggling it? selectAll() { for (let i = 0; i < this.suppliersCheckbox.length; i++) { if (this.suppliersCheckbox[i].type == " ...

Using Node.js to extract text from a local file on Azure using OCR technology

I recently started using the Azure OCR Service to extract text from images (https://learn.microsoft.com/de-de/azure/cognitive-services/Computer-vision/quickstarts/javascript#OCR). While things have been going smoothly so far with uploaded images, I am now ...

Guide to successfully passing a function as a prop to a child component and invoking it within Vue

Is it really not recommended to pass a function as a prop to a child component in Vue? If I were to attempt this, how could I achieve it? Here is my current approach: Within my child component - <template> <b-card :style="{'overflow-y&apo ...

TS2339: The attribute 'size' is not present on the 'string' data type

Within my Typescript file, I have the following line: return stringToValidate.length <= maxLength; Despite the code executing without issues, an error is displayed: TS2339: Property 'length' does not exist on type 'string'. I am cu ...

Transform any falsy values within a JavaScript object into an empty string

Looking for a solution to transform all undefined, NaN, etc. values in a Javascript object into an empty string for better definition. For example: javascriptObject = convertUndefined(javascriptObject) Seeking something that can achieve this functionalit ...

Issue with arrow function not being invoked in a React TypeScript component's prop inside a function

My parent component holds a useState hook to determine if the mobile Nav is open or closed: const [showMobileMenu,setShowMobileMenu] = useState<boolean>(false);. To close the mobile menu, I created an arrow function and passed it down to a child comp ...

Typescript is failing to infer the definition of an object, even after conducting a thorough check

I am encountering an issue with the code structure below: interface Data { isAvailable: boolean; } const foo = (data: Data | undefined, error: boolean) => { const hasError = error || !data; if (!hasError) { if (data.isAvailable) // do so ...

Determining data using the AngularJS Slider component

I am currently utilizing the angularJS slider from this source: https://github.com/venturocket/angular-slider The sliders are functioning correctly, but now I need to extract the values from them for basic calculations. The HTML code snippet is as follo ...

What is the best way to duplicate an entire webpage with all its content intact?

Is it possible to copy an entire page including images and CSS using Selenium? Traditional methods like ctrl + a or dragging the mouse over the page do not seem to work. How can this be achieved with Selenium without requiring an element to interact with? ...

Having trouble with npm global installation? Encountering the error message "Error: EACCES: permission denied

As the administrator of my MacBook, I am facing an issue while trying to run a npm command in my Django project. It is refusing to run due to missing permissions. (venv) jonas@Air-von-Jonas salaryx % npm install -g sass npm ERR! code EACCES npm ERR! syscal ...

Strategies for Creating a Test Suite for RepositoryFactory in Vue.js/Nuxt.js

Summary of RepositoryFactory Implementation An implementation of the RepositoryFactory pattern has been carried out for API connection in a Vue.js/Nuxt.js application. For more details, refer to this article: here hogeRepository.ts import { NuxtAxiosInst ...

Setting initial values for an object in JavaScript

I am currently seeking a method to store predefined values in a separate file for populating my function: Here is my function in index.js: const Modes = (array) => { return { name: array.name, funcionarioIncrease: array.funcio ...

JavaScript makes it possible to access subnodes in XML by utilizing specific methods and

I am looking to utilize javascript to extract data from an XML file that has been loaded into a webpage. Below is the XML file (a.xml) that I am working with. a.xml <?xml version="1.0"?> <Step rID="T6"> <Obj ><![CDATA[Get Data Ta ...

To get Protractor to work properly, I often find myself manually refreshing the page during the loading process

I am currently using Chrome as my browser. However, when I execute Protractor, the page starts to load but never completes loading until I manually refresh the page. After refreshing, everything runs smoothly. My page is built with Angular2 and is part of ...

Methods for adding a line to an array

I am currently working on a loop where I need to populate my array called photos: $scope.photos = []; var str = data.data.Photos; var res = str.split('|'); angular.forEach(res, function (item) { ...

React and Express are incompatible due to the error message "TypeError: undefined is not a function

I am attempting to display the data from this array on my website using react and express: [{"LocationName":"LIBERTY DOGS","Address":"105 Greenwood Ave N, Seattle WA","Available":"Y"},{"LocationName":"FREEDOM DOGS","Address":"105 Greenwood Ave N, Seattle ...

Yelp API call resulting in an 'undefined' response

When attempting to make an API call using the yelp-fusion, I noticed that the logged result is showing as undefined. It seems like this issue might be related to promises or async functions. It's important for me to maintain this within a function sin ...

Mastering the Art of Live Search in Drop Down Multi Select

I need to develop a search functionality similar to the one found on . This search should allow users to select options from a dropdown menu or type their own search query, and provide live search results. I attempted to use the jQuery plugin https://www.j ...