The mat-table's data source is failing to refresh and display the latest

When I click on a column header to sort the table, a function should trigger and update the data. However, the data is not updating as expected. Below is the code for the function and the table:

<table mat-table #table [dataSource]="dataSourceMD" matSort (matSortChange)="getRowMaximoTable($event)" matTableExporter #exporter="matTableExporter" #sortMD="matSort" class="tr_table">

    <ng-container *ngFor="let disCol of displayedColumnsMD; let colIndex = index"
        matColumnDef="{{disCol}}" [sticky]="isIn(disCol)">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>
            <div [innerHTML]="displayedColumnsNamesMD[colIndex]"></div>
        </th>
        <td mat-cell *matCellDef="let element"  [style.background-color]="element[disCol+'Color']" [style.color]="element[disCol+'Texto']">
            <div *ngIf="element[disCol]" [innerHTML]="element[disCol]"></div>
            <div *ngIf="!element[disCol] && !isIn(disCol)" [innerHTML]="'-'"></div>
        </td>
    </ng-container>

    <ng-container *ngFor="let filCol of displayedFilterColumnMD; let colIndexF = index"
        matColumnDef="{{filCol}}" [sticky]="colIndexF<3">
        <th mat-header-cell *matHeaderCellDef [style.text-align]="center" [attr.colspan]="1">
            <mat-form-field class="columnas" floatLabel='never'>
                <input matInput placeholder="Filter" type="text"
                    [(ngModel)]='filterTableMD[displayedColumnsMD[colIndexF]]'
                    name="displayedColumnsMD[colIndexF]"
                    (keyup)="hanlerOnChangeFilter($event, 'MD',displayedColumnsMD[colIndexF])">
                <button mat-button *ngIf="filterTableMD[displayedColumnsMD[colIndexF]]"
                    (click)="handlerClearFilterField('MD',displayedColumnsMD[colIndexF])" matSuffix
                    mat-icon-button aria-label="Clear">
                    <mat-icon class="material-icons-outlined">close</mat-icon>
                </button>
            </mat-form-field>
        </th>
    </ng-container>          

    <tr mat-header-row *matHeaderRowDef="displayedColumnsMD; sticky: true"></tr>
    <tr mat-header-row *matHeaderRowDef="displayedFilterColumnMD"></tr>
    <tr mat-row [ngClass]="{ 'maximo-row': i == indexMaximoMD }" *matRowDef="let row; columns: displayedColumnsMD; let i = index"></tr>

</table>

Function Code:

getRowMaximoTable(event?: MatSort) {
    let originalArrayData = [ ...this.dataSourceMD.data ];

    const valuesToSort = originalArrayData.slice(0, -4);
    const fixedValues = originalArrayData.slice(-4);
    const sortedArray = this.dataSourceMD.sortData(valuesToSort, this.dataSourceMD.sort);

    this.dataSourceMD.data = [...sortedArray, ...fixedValues];
}

I am trying to ensure that the data updates correctly when clicking on a column header.

Answer №1

My approach to solving this was as follows:

 In order to customize the sorting functionality, I utilized the dataSourceMD.sortingDataAccessor method. This allowed me to define specific sorting behavior based on certain conditions. For example, if the item being sorted is within the last 4 elements of the dataset and the sort direction is ascending, the value "ZZZZZ" is returned. On the other hand, if the item is in the last 4 elements and the sort direction is descending, the value "AAAAA" is returned. Otherwise, the default sorting based on the specified property is performed.

Answer №2

Is it possible to trigger Angular to execute change detection again in order to address this issue?

import { Component, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-dummy',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class DummyComponent {

  constructor(private cdr: ChangeDetectorRef) {}

  getRowMaximoTable(event?: MatSort) {
    let originalArrayData = [...this.dataSourceMD.data];

    const valoresArrayASortear = originalArrayData.slice(0, -4);
    const valoresArrayFijos = originalArrayData.slice(-4);
    const sortedArray = this.dataSourceMD.sortData(valoresArrayASortear, this.dataSourceMD.sort);

    this.dataSourceMD.data = [...sortedArray, ...valoresArrayFijos];
    this.cdr.detectChanges(); // prompting change detection to reassess the array
  }
}

Answer №3

If you want to retrieve the MatDataTable using viewChild, you can then utilize table.renderRows() to forcibly render it again. Alternatively, you could create a new MatDataTable.

@ViewChild('table') table!:MatTable
//or simply
//@ViewChild('table') table!:MatTable

//and then use:
this.table.renderRows()

Another option is:

this.dataSourceMD = new MatTableDataSource([...sortedArray, ...fixedValuesArray])
//Just remember that by creating a new MatDataTable, you will lose the matSort and paginator settings

this.dataSourceMD.sort = this.matSort  
this.dataSourceMD.paginator = this.paginator

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

How can AngularJS handle multiple routes using unique templates while sharing the same controller?

I am currently researching whether I can achieve the functionality described in the title. Here are my initial thoughts: Let's consider the following routes I have set up: .when('/', { templateUrl : 'partials/homepage.html&ap ...

There is no way to convert a strongly typed object into an observable object using MobX

I have been utilizing the MobX library in conjunction with ReactJS, and it has integrated quite smoothly. Currently, I am working with an observable array structured as follows: @observable items = []; When I add an object in the following manner, everyt ...

As I attempt to log in, the GitHub API is sending back a message stating that authentication

const fetchUser = async () =>{ let usernameValue : any = (document.getElementById('username') as HTMLInputElement).value; let passwordValue : any = (document.getElementById('password') as HTMLInputElement).value; const ...

Is there a way to retrieve text content from a modal using JavaScript?

I am using ajax to fetch values from my table. $(data.mesIzinTanimList).each(function (index, element) { if (element.izinTanimiVarmi == 'yok') tr = "<tr class='bg-warning text-warning-50' row='" + element. ...

Utilizing multiple address parameters within a single-page application

Apologies for the lengthy post. I have encountered an issue with my code after running it through a bot that I can't seem to resolve. In my code, I aim to create functionality where you can visit the address #two, followed by two separate parameters ...

Manipulating SVG image color using JavaScript

Is there a way to change the colors of an svg image using Javascript? Perhaps by loading it as an object and accessing the color/image data? I would greatly appreciate any responses or tips on this matter! ...

Error: Could not locate application for Ionic Serve command

I have been developing a project in Ionic2 on another computer. However, when I try to run ionic serve on my PC, an error message appears: 192.168.1.100:8100 Application not found I have configured my app to use a static IP address... How can I resolve ...

What is the best way to retrieve data from multi-dimensional JSON structures?

Looking to extract specific values from my JSON file. console.log( objects.assignments.header.report_type ); I need to display HOMEWORK Javascript $.ajax({ url: "/BIM/rest/report/assignment", type: "POST", dataTyp ...

Conversation panel text slipping out of <div>

I am currently working on creating a mock "chat" feature. The issue I am facing is that when I repeatedly click the "send" button, the text overflows from the div. Is there a way to prevent this by stopping the text near the border of the div or adding a s ...

How to style large numbers with AngularJS

I'm facing a challenge with large numbers in a table and I'm seeking a solution to format them, ideally as $13b, $10m... Has anyone encountered this issue before and discovered a customized filter or solution for it? Appreciate any help! ...

Tips for maintaining the size of an object while resizing a window

My circles are designed to increase in width at regular intervals, and once they reach a certain scale, they disappear and start over. However, every time I resize the screen or zoom in and out, the circle gets distorted into an oval or stretched object. H ...

I am having trouble installing the latest version of Bun on my Windows operating system

When attempting to install Bun on my Windows laptop using the command npm install -g bun, I encountered an error in my terminal. The error message indicated that the platform was unsupported and specified the required operating systems as darwin or linux w ...

Support for ViewEncapsulation.ShadowDom now available in Edge, Internet Explorer, and legacy browsers

I am working with Angular 7 and material design. Some of my components utilize ShadowDOM ViewEncapsulation, leading to errors in older versions of IE, Edge, Chrome, and Firefox. Below is the error message I am encountering: Object doesn't support pr ...

Searching function in material-table does not work properly with pipe symbol

Within my data table, I utilize the @pipe to display name instead of position in the position row... The name is sourced from a separate JSON file... <ng-container matColumnDef="position"> <mat-header-cell *matHeaderCellDef> No. </ma ...

What is the best way to extract a CSS rule using PHP?

Below is an example of the stylesheet I am currently using: #thing { display: none; } I am looking to retrieve the value of the 'display' property using PHP instead of Javascript. While I know how to do this with Javascript, I would prefer to u ...

Deciphering the TypeScript type in question - tips and tricks

One of my abstract classes includes a static property with various properties, where default is consistently named while the others may have random names. public static data = { default: { //only this one always have 'dafault' name na ...

Establishing a pre-selected option in a drop-down menu

I am working on a dropdown list and my goal is to have the default option selected when the page loads <b>Filter Within Months:</b> <select class="btn green" ng-model="myOptions" ng-options="i.label for i in items track by i.id" ng-change= ...

What is the best way to add data-content to hr:after using JavaScript?

Adding style to an element in javascript can be simple. For example: myElement.style.color = "red"; However, what if I wanted to achieve something like this: hr:after { content: "myRuntimeValue" } Is there a way to do this using javascript? ...

Customizing font color upon hover in Next.js and Tailwind.css

Recently, I developed a Navbar component that displays a purple link when navigating to pages like Home or Projects. The issue arises when the background color is light; in this case, the link turns green on hover instead of staying purple. How would I adj ...

Using AngularJS to Apply a Class with ng-repeat

Using ng-repeat in my markup, I am trying to add text to each li element and also include an additional class (besides the 'fa' class). This is what I have done so far: <ul class='social-icons' ng-repeat="social in myCtrl.socialArr" ...