Tips on retrieving filtered data from the datasource using the isAllselected function, specifically in the checkbox list function "isAllSelected" within Angular 7

I am currently working with a mat table that has checkboxes for selecting all/row items and a filter function. When I apply a filter to the data source, I want to retrieve all the filtered data from this source.

After correctly applying the filter, I can see the filtered data in my mat table showing only the filtered items. However, when I try to select all rows using the "select all" checkbox in the mat-header, the filtered item rows are selected on the front end but upon checking through the debugger, I notice that while all rows are selected in the selected row array, the required filtered data rows are not present in the data source. How can I resolve this issue? If anyone knows of an example URL demonstrating this solution, please leave it in the comments.

Here is some sample code:

<mat-form-field appearance="outline">
    <mat-label>Search</mat-label>
    <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Search">
    <mat-icon matSuffix style="font-size: 16px;">search</mat-icon>
</mat-form-field>

<table mat-table #table [dataSource]="dataSource">
    <ng-container matColumnDef="select">
        <th mat-header-cell *matHeaderCellDef>
            <mat-checkbox (change)="$event ? masterToggle() : null"   [checked]="selection.hasValue() && isAllSelected()"
                [indeterminate]="selection.hasValue() && !isAllSelected()">
            </mat-checkbox>
        </th>
        <td mat-cell *matCellDef="let row">
            <mat-checkbox (click)="$event.stopPropagation()"
                    (change)="$event ? selection.toggle(row) : null"
                    [checked]="selection.isSelected(row)">
            </mat-checkbox>
        </td>
    </ng-container>

    <ng-container matColumnDef="id">
        <th mat-header-cell *matHeaderCellDef ><b>S.No.</b></th>
        <td mat-cell *matCellDef="let element; let i=index">{{i+1}}</td>
    </ng-container>

    <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef  mat-sort-header="name">
            <b>Office Name</b>
        </th>
        <td mat-cell *matCellDef="let element"> {{element.name }} </td>
    </ng-container>

    <ng-container matColumnDef="contactPerson">
        <th mat-header-cell *matHeaderCellDef mat-sort-header="contactPerson"><b>Contact Person</b></th>
        <td mat-cell *matCellDef="let element"> {{element.contactPerson}} </td>
    </ng-container>

    <ng-container matColumnDef="phone">
        <th mat-header-cell *matHeaderCellDef mat-sort-header="phone"><b>Mobile No</b></th>
        <td mat-cell *matCellDef="let element"> {{element.phone}} </td>
    </ng-container>

TS code:

applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
}

isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
}

masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
}

Answer №1

Although this post may seem dated, I wanted to share how I successfully tackled a similar issue. Within your user interface, trigger the click event:

<mat-checkbox (change)="$event ? masterCheckboxToggle($event.checked) : null"  [checked]="selection.hasValue() && isAllSelected()"
                 [indeterminate]="selection.hasValue() && !isAllSelected()">  </mat-checkbox>

Utilize filtered data in your back-end for selection purposes:

masterCheckboxToggle(event: boolean) {
   this.selection.clear();
    
   if(event){
      this.dataSource.filteredData.forEach(row => this.selection.select(row));
   }
}

Answer №2

Regardless of the situation, this solution will be effective for you.

toggleAllItems() {
this.isAllSelected() ?
    this.selection.clear() :
    this.matDataSource.filteredData.forEach(row => this.selection.select(row));

}

This function handles scenarios where filtered data contains all records by default but narrows down when filtering is applied to the table.

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

Define the interface for a GraphQL resolver argument in code-first implementation

This specific GraphQL schema example from the Constructing Types page showcases how to define the Query type. // Creating the Query type var queryType = new graphql.GraphQLObjectType({ name: 'Query', fields: { user: { type: userType ...

What is the best way to convert canvas data into a string in Angular once the user has made a drawing on it?

I need help figuring out how to automatically store canvas data to a variable in Angular whenever the user draws or makes changes to it. Here is a snippet from my component.html file: <canvas id="canvas"></canvas> And here is part o ...

A guide on converting array values to objects in AngularJS HTML

Here is my collection of objects: MyCart = { cartID: "cart101", listProducts : [ {pid:101, pname:"apple", price: 200, qty:3}, {pid:102, pname:"banana", price: 100, qty:12} ] } I have incorporated a form in ...

Additional items to undergo filtering within my Angular project

I am currently working on a test project and I have implemented a filter to search for the last name of users in my list. However, I now want to enhance this filter to search by not only last names but also first names, email addresses, and usernames. I ha ...

Integrate a dynamic component into the Angular 7 template

The code I am working with currently has a scenario where during the ngOnInit() execution, the correct component is stored in this.widget, along with appropriate data in this.data. I encountered difficulty trying to smoothly integrate the dynamic componen ...

Stop modal from closing in the presence of an error

My approach involves using a generic method where, upon adding a food item, a modal window with a form opens for the user to input their details. However, since backend validation for duplicate items can only be retrieved after the API call completes. I w ...

Upgrading from Ionic 3 to Ionic 5 API: A Comprehensive Guide

Hey there, I'm currently working on transitioning my Ionic 3 project to Ionic 5. While I've got a good handle on the component migration process, I'm running into an issue with Http, which is no longer supported. In the past, I used to call ...

Error encountered during Angular CLI's production build: TypeError - Attempting to access property 'kind' of an undefined value

To view the error message, click here { "@angular-devkit/build-angular": "~0.803.19", "@angular/cli": "~8.3.19", "@angular/compiler-cli": "~8.2.14", "@angular/language-service": "~8.2.14", "@types/jasmine": "~3 ...

Utilizing the slice method within an ngFor loop in Angular for multiple iterations

Looking to divide the nested ngfor loop into 3 sections <div class="row" *ngFor="let row of matrix; index as i"> <div class="col" *ngFor="let col of row; index as j"> <div *ngFor="let placeho ...

Expanding Typescript modules with a third-party module and namespace

Looking to enhance the capabilities of the AWS SDK DynamoDB class by creating a new implementation for the scan method that can overcome the 1 MB limitations. I came across some helpful resources such as the AWS documentation and this insightful Stack Over ...

Unexpected issue encountered during the Angular 9 compilation process

Since migrating to Angular 9, I've encountered an issue with my feature branch after a rebase. Trying to switch to develop and update it using pull origin develop, everything seemed fine until I came across this error that's leaving me puzzled: h ...

Can a client application access a token and client_id from the GITHUB API without a server involved?

Is there a way to access data from the GitHub API in my Angular application without requiring a server component? Can I pass along username and password or a personal token to authenticate with GitHub? I want to retrieve information from the GitHub API, b ...

When "console.log" is included as an argument in the subscribe() method for an observable

Typically, when I want to display some results from an observable, my process usually looks like this. const source = interval(3000); const transform = source.pipe(scan((acc, num) => [...acc, num], [])); transform.subscribe(res => console.log("% ...

Innovative feature: Customizable dropdown options in PrimeNg for Angular 4

As a beginner in UI development and PrimeNg, I may be missing something obvious here. I am currently working on a ngFor loop to create multiple levels of dropdowns. For example, I have two rooms - Deluxe and Suite. The Deluxe room has rates for Breakfast, ...

Guide to combining an Angular 2 application with a Django application

Currently, I have been working through the Tour of Heroes tutorial. The structure of my Django app can be simplified as shown below: apps/my_app/migrations/ apps/my_app/__init__.py apps/my_app/urls.py apps/my_app/views.py frontend_stuff/js/ javascript ...

Is there a way to extend RouteComponentProps in order to accommodate additional props?

I am encountering an issue with this piece of typescript code in a React render props component. The error is related to the fact that RouteComponentProps does not contain a prop called 'component'. class Auth extends Component<RouteComponent ...

Make sure to include `jquery` in the types section of your tsconfig file

I've encountered an issue while trying to use jQuery in my Angular-TypeScript project. After installing jquery using "npm install @type/jquery", I am receiving the following error when trying to serve: Error TS2592: Cannot find name '$'. Is ...

Angular is showing an error stating that there is no 'pipe' property on the type 'HttpParams'

Recently, I embarked on my journey to learn Angular. While perusing a guide on YouTube, I encountered an error while trying to replicate the code. Here's my objective: I aim to fetch data from fakestoreapi.com/products that aligns with my defined in ...

The data structure does not match the exact object type

Why isn't this code snippet functioning as expected? It seems that 'beta' has keys of type string and their values are compatible (id is a number type, and temp is also a number type). Additionally, the Record function should make the values ...

Ways to dynamically configure Angular form data

Below is an Angular form group that I need help with. My goal is to initialize the form and if there is no data coming into the Input() data property, then set the form values as empty strings '' for user input. However, if there is indeed form d ...