What is the best way to exclude the bottom four rows when sorting with MatSort?

Is there a way for me to keep the last four rows fixed when sorting the table based on the column header? Here is an image of the table: table image

<table mat-table [dataSource]="dataSourceMD" matSort (matSortChange)="getRowMaximoTable('dataSourceMD', 'indexMaximoMD')" 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>

How can I make sure that the last four rows in this Angular Material table stay fixed even when sorting using the matSort attribute?

Answer №1

Divide the array of objects in half using splice, then sort the first half.

const sortedArray = [...data];
let unsortedSegment: any[] = [];
if(sortedArray.length >= 4) {
  unsortedSegment = sortedArray.splice(-4);
}
const sortedHalf = sortedArray.sort((a, b) => {
  //sorting logic
});
this.finalSortedData = [...sortedArray, ...unsortedSegment];

Check out the StackBlitz example here: https://stackblitz.com/edit/cnc-mat-table-custom-sort

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

Incorporating external files into Javascript code may cause issues with its functionality

Currently, I have a fully developed PHP theme that I am in the process of designing. Within this theme, I have integrated an image slideshow plugin to enhance its functionality. The following code represents the implementation of the image slideshow: &l ...

A guide on streamlining the process of generating "this." variables within Angular

When it comes to working with Javascript, particularly Angular, I find myself using the this. syntax quite often. I'm curious to know if it's possible to concatenate variables in order to create a this. variable. For instance, is this achievab ...

Whenever I attempt to make changes to the React state, it always ends up getting reset

Currently, I am attempting to utilize Listbox provided by Headless UI in order to create a select dropdown menu for filtering purposes within my application. However, the issue I have encountered is that whenever I update my "selectedMake" state, it revert ...

"Vue.js: The Ultimate Guide to Event Management and Data Handling

I recently started learning Vue.js and I'm having some difficulty with my coding exercises: The task is to have a menu button that opens a dropdown box when clicked, and when any selection is made, it should go back to the menu button. index.js cons ...

transmitting biscuits in an Angular application and managing Access-Control-Allow-Origin during development phase

Currently, I am developing two Angular apps that are running on different ports: https://app.example.com:4202 and https://app2.example.com:4203. Both of these apps rely on a backend located at https://example.com. Within my backend PHP pages, there is a u ...

Utilizing ControlValueAccessor in various components

I am currently working on a component that implements the ControlValueAccessor interface, and I am facing some difficulties in understanding how to properly utilize it: // Angular Imports import { Component, OnInit, forwardRef, Output, EventEmitter, OnC ...

Having trouble importing AnimeJS into an Ionic-Angular project

I successfully added AnimeJS to my Ionic 4 project using the commands below: npm i animejs --save npm i @types/animejs --save To reference AnimeJS, I used the following import statement: import * as anime from 'animejs' However, whenever I tr ...

"In strict mode, the object is subjected to specific rules

I am facing a challenge with an object in my project that needs to run the content of the page within strict mode. Even after attempting to return it for global scope usage, I still haven't been able to resolve the issue. (function($) { "use stric ...

Embed API allows users to showcase a variety of charts all on one page

I am trying to incorporate two google analytics timeline charts using the embed API on a single page. However, I am facing an issue where only one chart is appearing. The first chart should display bounce rate data and the second chart should display sessi ...

What is the best way to extract data from an [object Object] and store it in an Array or access its values in Angular?

My Angular code is written in the component.ts file. I am fetching data from a backend API and using console.log to display the data. getInfo() { const params = []; params.push({code: 'Code', name: 'ty_PSD'}); params ...

What is the best way to use Jquery ScrollTo() to navigate to an element on a page using a class selector

Building on the information from this source, I have a question: How can I resolve the same issue using a class selector like $('.class')? I am encountering an error message that says Uncaught TypeError: undefined is not a function This occurs ...

Using jQuery to include Chinese characters in a request header

When making a jQuery post request, I need to set client information in the header. This is how my call looks: jQuery.ajax({ url : myURL, type : "POST", beforeSend : function(request){ request.setRequestHeader('someInfo', clie ...

Step-by-step guide on developing an AngularJs provider using TypeScript

As I've developed a Directive that incorporates various Css classes, it would greatly enhance its flexibility if the Css classes could be configured at Application start within the config section. I believe utilizing a provider is the appropriate appr ...

React-highlightjs failing to highlight syntax code properly

I'm currently using the react-highlight library to highlight code snippets in my next.js application. However, I've encountered an issue with the code highlighting when using the a11y-dark theme. https://i.stack.imgur.com/ip6Ia.png Upon visitin ...

Can integers be used as keys in a JavaScript object's storage?

Currently, I am in the process of creating a JSON index file to serve as a database index for a javascript application that is currently under development. The structure of my index will resemble the following: { "_id": "acomplex_indice ...

Navigate through the list of options by scrolling and selecting each one until the desired element is

Hey, I've got this AngularJs directive that selects an item based on the "key-pressed" event, and it's working perfectly. The issue arises when there is a scroll bar since the elements get hidden, making it difficult for me to see them. You can ...

Retrieve the highest value from 4 different JSON source URLs

After retrieving values from a JSON URL, using the following code: $(document).ready(function () { function price(){ $.getJSON('https://poloniex.com/public?command=returnTicker', function(data){ document.getElementById('Polon ...

Can anyone provide a solution for determining the number of active intervals in Javascript?

Similar Question: How to View All Timeouts and Intervals in JavaScript? I've been working on an HTML5 game that includes a lot of graphical effects using intervals created by the setInterval function. However, I've noticed that my game is ru ...

"Troubleshooting issue: Unable to retrieve grid data from Google Sheets API v4 when integrated

I've implemented a function within a React component that retrieves JSON data from an API request and logs it: async function getAllSheets() { let response; try { response = await window.gapi.client.sheets.spreadsheets.values.batchGet( ...

A guide on integrating Pug templating engine with ReactJS

For the integration of Pug with a freshly created ReactJS application, I followed these steps: 1. Started by creating a new ReactJS app using create-react-app 2. Next, I referred to the instructions on babel-plugin-transform-react-pug for installing the ...