No data found in the subrow of the datasource after the filter has been

I am working with a material table that has expandable rows. Inside these expanded rows, there is another table with the same columns as the main table. Additionally, I have implemented filters in a form so that when the filter values change, I can update the dataSource accordingly.

Upon page initialization, I retrieve data for the table and store the results in a global variable. In the ngOnInit function, I subscribe to the valueChanges event of the form. However, I am encountering some challenges in this process. When I declare a variable based on the allData variable and attempt to filter on subRows within the dataSource, it inadvertently changes the data in the allData variable. Filtering at the first level does not pose any issues.

public allData;
public dataSource;

public ngOnInit(): void {
   this.allData = this.service.getData(someProperties);
   this.filterForm.valueChanges.subscribe((filters) => {
      this.filterDataSource(filters);
   });
}

public filterDataSource(filters) {
   let filteredData = this.allData;

   // Applying filters at the main level works fine
   // No change observed in this.allData
   filteredData = filteredData.filter((x) => {
      return x.property.includes(filters.search);
   });

   // Sublevel filtering encounters issues
   // Changes detected in this.allData
   // The subRow in this.allData becomes empty after clearing the search
   // If the filter did not find anything during application
   for(let index = 0; index < filteredData.length; index++) {
      filteredData[index].subRows = filteredData[index].subRows.filter((x) => {
         x.property.includes(filters.search);
      });
   }
   

   this.dataSource.data = filteredData;
}

The outcome of a search action and subsequent removal of the search term are as follows:

// Before applying the filter
allData = [
   {
      property: 'present', 
      subRow: [{
         property: 'I'm here'
      }]
   },
   {
      // Additional entries
   }

]

// After clearing the filter
allData = [
   {
      property: 'present', 
      subrow: []
   },
   {
      // Additional entries
   }
]

Answer №1

To create a comprehensive duplicate of allData, you can utilize the cloneDeep method which is available in lodash library. More details on how to implement it can be found here.

let filteredData = cloneDeep(this.allData);
// Proceed with your filtering process as usual

If using lodash is not an option for you, then manual copying becomes necessary. Assuming that your data structure remains consistent with the one you provided:

const filteredData = this.allData.filter((x) => {
  return x.property.includes(filters.search);
}).map((data) => ({...data}));
// It's worth mentioning that while this solution may not perform a deep copy, it should suffice given the nature of your data filtering.

To delve deeper into understanding object references:

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

Sharing an object with a child component in Angular 2

After receiving data from a subscription, I am encountering an issue where my data is not binding to the local variable as expected. The scenario involves two components and a service. The parent component triggers a method in the service to perform an HT ...

Having difficulty initializing a constant object in TypeScript

Encountering an error while attempting to compile my code using Angular 7.2.0 and TypeScript version 3.2.2: Error TS1005: ',' expected.**… The issue seems to be arising from the line where I am trying to define a const object. addAppareil( ...

Creating Dynamic HTML/DOM in Angular 14: A Guide for Adding New Items to a List

I am currently iterating through a list of items and displaying them within a div element. These items are rendered when the page initially loads. <button (click)="addCut()" mat-raised-button color="primary">Add New Cut</button ...

Changing the title dynamically for the Global NavBar in Ionic 2

I have been working with the Nav component in Ionic 2 and I'm facing a challenge. I want to maintain a global header with left and right menus while changing the title dynamically as I navigate through different root pages. Here is the code snippet th ...

The OR operator in TypeORM allows for more flexibility in querying multiple conditions

Is there any OR operator in TypeORM that I missed in the documentation or source code? I'm attempting to conduct a simple search using a repository. db.getRepository(MyModel).find({ name : "john", lastName: "doe" }) I am awar ...

Struggling to implement the proper authentication method with API in Ionic

Having an API for the login, but being new to Ionic is causing difficulty in creating the correct method for the login process. The service file is located here: providers/restapi/restapi.ts import { HttpClient } from '@angular/common/http'; im ...

Utilizing React Typescript for Passing Props and Implementing them in Child Components

I'm currently working with React and TypeScript and attempting to pass data as props to a child component for use. However, I've encountered an error that I can't quite understand why it's happening or how to resolve it. Additionally, I ...

What is the process for setting up a resthook trigger in Zapier?

I'm currently integrating Zapier into my Angular application, but I'm struggling with setting up a REST hook trigger in Zapier and using that URL within my app. I need to be able to call the REST hook URL every time a new customer is created and ...

How to avoid property sharing in Angular recursive components

I am currently working on a recursive component that generates a tree structure with collapsible functionality. However, I am facing an issue where the state variable active is being shared among child components. Is there a way to prevent this from happen ...

Is there a way to properly install angular cli that is compatible with node version 13.14.0?

Running Windows 7, I attempted to install an outdated version of node - specifically node 13.14.0. However, when trying to install the Angular CLI with the command "npm i -g @angular/cli", an error occurred. Can anyone advise on what steps I should take ne ...

The custom pattern validation for Formly Email is malfunctioning

Is there a way to validate email input using ngx-formly? I attempted the code below but it didn't work as expected app.module.ts export function EmailValidator(control: FormControl): ValidationErrors { return /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a ...

The 'mat-table' component is triggering an error indicating that the 'dataSource' attribute is unrecognized in the table

Recently, I have been diving into the world of Material Library for Angular. Working with Angular version 15.0.1 and Material version 15.0.1, I decided to include a mat-table in my form (schedule.allocator.component.html): https://i.stack.imgur.com/c7bsO. ...

What is preventing the exclusion of the null type in this specific situation within Typescript?

type NonNullableCopy<O> = { [p in keyof O] -?: O[p] extends null | undefined ? never : O[p]; }; type Adsa = {a?: number | null} type Basda = NonNullableCopy<Adsa> let asd : Basda = { a: null // Still valid. No errors } Although it see ...

The 'MutableRefObject<null>' type is lacking the following properties that are present in the 'Element' type

I'm eager to implement intersection observer in my React Typescript project. (https://www.npmjs.com/package/react-intersection-observer) However, I encountered an issue with setting the root: const root = useRef(null); const { ref, inView, entry } ...

Load a lazy module in Angular that contains a nested router-outlet

I am encountering an issue with my Angular CLI application that has multiple lazy loaded modules, some of which have their own router-outlets. When trying to directly route to a specific path in a lazy loaded module, it seems like the browser is attempting ...

I'm attempting to retrieve an image from the database to display in the modal, but unfortunately the image isn't appearing as expected within the modal

I have the following code snippet for fetching an image: <img src="pics/file-upload-image-icon-115632290507ftgixivqp.png" id="image_preview1" class="img-thumbnail" style="margin-top: 15px; height:50%; width:20%"&g ...

Issues have been encountered with Angular 5 when trying to make required form fields work properly

Just created my first Angular app using Angular 5! Currently following the documentation at: https://angular.io/guide/form-validation. Below is the form I have set up: <form class="form-container"> <mat-form-field> <input matInput pl ...

Preserving selected items in ag-grid when refreshing data sources

Just to clarify, this code snippet pertains to Angular 7 Interestingly, there is not much information available on this specific issue. I have a solution that is "working," but there is a minor issue with it. Essentially, I am calling an endpoint at regul ...

Ending the connection in SignalR upon $destroy

I am currently working on a page that is utilizing SignalR, Angular, and Typescript. Upon the destruction of the current $scope (such as during a page change), I make an attempt to disconnect the client from the SignalR server: Controller.ts $scope.$on(&q ...

What is the process for exporting the reducer function and integrating it into the storeModule.forRoot within an Angular application?

Recently, I started delving into ngrx and decided to educate myself by going through the official documentation on their website ngrx.io. During this exploration, I came across a puzzling piece of code in one of their reducers. The file in question is cou ...