What steps are required to utilize NgbSortableHeader for sorting a bootstrap table through programming?

I have a bootstrap HTML table (operated by ng-bootstrap for Angular and utilized NgbdSortableHeader to arrange table columns by clicking on the column). When I click on an element, it sorts the column in ascending, descending, or ''(none) order.

HTML TABLE HEADERS

 <tr>
    <th scope="col">#</th>
    <th scope="col" sortable="name" (sort)="onSort($event)">Country</th>
    <th scope="col" sortable="area" (sort)="onSort($event)">Area</th>
    <th scope="col" sortable="population" (sort)="onSort($event)">Population</th>
  </tr>

SORTING METHOD

      @ViewChildren(NgbdSortableHeader) headers: QueryList<NgbdSortableHeader>;
    
      onSort({ column, direction }: SortEvent) {
        // resetting other headers
        this.headers.forEach(header => {
          if (header.sortable !== column) {
            header.direction = "";
          }
        });
    
        // sorting countries
        if (direction === "") {
          this.countries = COUNTRIES;
        } else {
          this.countries = [...COUNTRIES].sort((a, b) => {
            const res = compare(a[column], b[column]);
            return direction === "asc" ? res : -res;
          });
        }
  }

Whenever onSort is triggered via clicking on a column header, it arranges the countries array and updates the table accordingly.

  ngOnInit() {
    this.onSort({ column: "population", direction: "asc" });
  }

However, when calling the onSort method in onInit(), it doesn't work. How can I make this function work programmatically by calling the onSort function?

Link to functional StackBlitz example: https://stackblitz.com/edit/ngbootstrap-table-sorting-vfwu4m?file=app/table-sortable.ts

Answer №1

To ensure that the table has been rendered before attempting to sort it, use AfterViewInit instead of OnInit. The AfterViewInit lifecycle hook is called after the component and any child components have finished rendering, allowing you to sort the table at that point. For more information on lifecycle hooks, refer to this link.

If you want the sorting direction arrows to be visible when sorting programmatically, you must update the sorting code from:

this.onSort({ column: "population", direction: "asc" });

to:

let populationHeader = this.headers.find(h => h.sortable === "population");
populationHeader.sort.emit({ column: "population", direction: "asc" });
populationHeader.direction = "asc";

The line

populationHeader.direction = "asc";
ensures that the sorting arrow appears on the header column in the table.

Therefore, the updated NgbdTableSortable component will look like this:

export class NgbdTableSortable implements AfterViewInit {

  ngAfterViewInit() {
    console.log("afterViewInit working");
    let populationHeader = this.headers.find(h => h.sortable === "population");
    populationHeader.sort.emit({ column: "population", direction: "asc" });
    populationHeader.direction = "asc";
  }
 
  ...
}

For a demonstration, check out this Stackblitz.

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

Utilizing Electron API within an Angular Component

I'm hoping to utilize a locally stored video file in electron and play it within my angular component. Despite exposing the loadLocalFile function to prevent the need for setting nodeIntegration to true, I keep receiving a Security Warning : This re ...

What is the reason that Jest is not able to spy on the function?

A custom Hook was developed with only one function being imported. Ensuring this function is called with the correct arguments is crucial. import { IsValueAlreadyRegistered } from "../../entities/registration/actions"; export const useForgetPass ...

Exploring the capabilities of Ionic 3 when integrated with storage

In my Ionic 3 application, I am utilizing the storage feature. To start with, I import storage in the app.module.ts file. import { IonicStorageModule } from '@ionic/storage'; imports: [ IonicStorageModule.forRoot() ] I have developed an Ecomm ...

How to integrate external JavaScript files with Angular CLI and Webpack

I'm facing a challenge on how to incorporate JS files (vendors) after transitioning Angular Cli from SystemJs to Webpack. For instance Option A I have npm-installed js files. Simply adding script tags to the head tag doesn't work, and it doesn ...

The functionality of CDK Drag Drop is not accurately adjusting the placement of images

I have implemented an image gallery and am working on rearranging the position of the images using the Drag & Drop cdk library. However, I am facing an issue where the swapping of images does not always occur correctly; sometimes when attempting to exchan ...

Replacing `any` in TypeScript when combining interfaces

Currently using Express and attempting to explicitly define res.locals. Issue arises as in the @types/express package, Express.Response.locals is declared as any, preventing me from successfully overwriting it: types/express/index.d.ts: declare namespace ...

Retrieve the TaskID of an ECS Fargate container for exporting and future use within AWS CDK code

Currently, I am leveraging CDK version 2 alongside Typescript. In my current setup, I encounter a situation where I necessitate the TaskID value from ECS Fargate Container to be incorporated into another command. The process involves me utilizing new ecs ...

Transferring Startup Information to Angular 2

Is there a way to pass initialization data into an Angular 2 application created with Angular CLI? I have an Access Token from a pre-authenticated .NET backend that I need to use to call an API. I attempted to do this through a local web API endpoint, but ...

Error with Background component in Next.js-TypeScript when trying to change color on mouseover because Window is not defined

Within my Background component, there is a function that includes an SVG which changes color upon mouseover. While this functionality works fine, I encountered an error when hosting the project using Vercel - "ReferenceError: window is not defined." This i ...

Tips for transforming a JSON Array of Objects into an Observable Array within an Angular framework

I'm working with Angular and calling a REST API that returns data in JSON Array of Objects like the example shown in this image: https://i.stack.imgur.com/Rz19k.png However, I'm having trouble converting it to my model class array. Can you provi ...

Using Ionic 2 to close the FAB menu with a button press

Is there a way to automatically close the FAB menu when a button inside it is pressed? Take a look at the button: <ion-fab bottom center > <button ion-fab><b>Hello</b></button> <ion-fab-list side="top"> <button ion- ...

Initiating change notification when utilizing service communication

So I am facing an issue with two unrelated components where I am attempting to establish communication between them using a service and a BehaviorSubject. Despite successfully exchanging data, calling the service from one component does not trigger change ...

Webpack is encountering difficulties in locating the entry module when working with typescript

I've been working on integrating webpack into my typescript application. To get a better understanding of webpack, I decided to do a minimal migration. I started by cloning the Angular2 quickstart seed and added a webpack.config.js: 'use strict& ...

Development in Angular 2 with a team of developers utilizing TFVC for version control and managing node_modules

With over 20,000 files in the node_modules directory, it may not be practical to include them in source control. This results in developers having to run 'npm install' every time they perform a 'get latest' in order to download any mis ...

Assigning a click event to an element within CKEditor

Looking to add a click event to an element in ckeditor4-angular for custom functionality <div class="fractional-block" id="fractional-block"><span>5</span><svg height="5" width="100%"><line ...

The Next.js API has a mysterious parameter that remains undefined

I currently have a component implemented import React, { useEffect } from "react"; import styles from "../styles/success.module.css"; import { useRouter } from "next/router"; import axios from "axios"; const Success ...

The Influence of Getter Performance in Angular Templates

As I delve into an existing Angular application, I've noticed a pattern where values used in templates across many components are actually properties that are being accessed through getters and setters without any additional logic: <input type="nu ...

Implementing Bootstrap 3 mobile design by necessity

My Wordpress site uses a Bootstrap 3 layout where the loop displays posts using 2 different templates. Type 1 <div class="row"> <div class="col-md-4"> <h1>title</h1> <h3>sub</h3> </div> ...

Tips for defining the anticipated server response solely based on status and cookie

I am using Redux Toolkit Query to occasionally refresh the jwt token: import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; export const refreshApi = createApi({ reducerPath: "apiSlice", baseQuery: fetchBaseQuer ...

Encountering a failure in library construction while using Angular 9

Currently, I am in the process of updating this library https://github.com/flauc/angular2-notifications from Angular 2+ to Angular 9. The initial error was related to the ModuleWithProviders becoming a generic type, which I have successfully addressed. Ad ...