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

Encountered an issue with ionViewDidLoad: The property 'firstChild' cannot be read as it is null

While working on an Ionic 2 App with Angular2 and Typescript, I encountered an issue when trying to pass a JSON to map for markers. Here is the link to the gist containing the code snippet I am facing an error that reads: view-controller.js:231 MapPage i ...

When attempting to create a new page in Ionic 5, the error message "**An NgModule could not be located**" is being displayed

While attempting to create a page using ionic g page pages/first, I encountered the following error: Could not find an NgModule. Use the skip-import option to skip importing in NgModule. [ERROR] Could not generate page However, when I tried ionic g page s ...

Transferring data from a child to a parent component in Angular 2 using a combination of reactive and template-driven approaches

Recently delving into Angular 2 ( and Angular overall ) , I found myself at a crossroads with my co-worker. He opted for the template-driven method while I leaned towards the reactive-driven approach. We both built components, with his being a search produ ...

Angular 2 Mixup: Using Leaflet and Google Maps with Incorrect Tile Order

I am encountering an issue while working on Leaflet and Google within Angular 2. The problem lies in the Tilemill tiles not rendering properly as they are displaying in a strange order. Here is a screenshot of the current state: https://i.stack.imgur.com/ ...

What exactly does the ".subscribe" function do within Angular framework?

Currently, I am exploring the angular-tour-of-heroes application and came across the .subscribe method in routing. Can anyone provide an explanation of what is happening in this code snippet? If you'd like to check out the app yourself, here's t ...

Loading the value of a Subject variable in an Angular 2 application using Typescript

I am currently developing an Angular2 application where I am loading data from a service into my component as a subject. public type1Choisi: any; constructor( public formeService: FormeService, ...) { this.formeService._type1.subscribe(type1 => ...

Accessing Parent Component's Route Parameters in Child Component in Angular 5

Here we have the add-new-folder.component, which functions as a child component of the folder.component. When routing to the add-new-folder.component from the parent folder.component, I need to access the userid parameter of the parent component in its chi ...

Angular does not seem to be identifying the project name as a valid property

After installing Angular materials using the CLI, I decided to check my angular.json file and encountered an error in the console stating that "Property MEAN-APP is not allowed". [The name of my Angular project is MEAN-APP] Here's a screenshot of the ...

The issue with ngx-bootstrap-modal is that it fails to interpret HTML elements

In my Angular 5 project, I am implementing ngx-bootstrap-modal. Below is the code I am using to open the modal: this.dialogService.addDialog(PopUpComponent, { title: 'Custom locale', message: "Hello ? " }).subscribe((isConfirmed ...

Generic Abstract Classes in TypeScript

In my TypeScript code, I have an abstract generic class with a method that takes a parameter of a class type variable. When I tried to implement the abstract method in a derived class, I noticed that the TypeScript compiler doesn't check the type of t ...

The unexpected identifier 'express' was encountered in the import call, which requires either one or two arguments

I'm in the process of constructing an express server using typescript and Bun. Recently, I completed my register route: import express from "express"; const router = express.Router(); router.get('/registerUser',(_req:express.Reque ...

Date input using manual typing format

I've implemented the ng-pick-datetime package for handling date selection and display. By using dateTimeAdapter.setLocale('en-IN') in the constructor, I have successfully changed the date format to DD/MM/YYYY. However, I'm facing an iss ...

Should we use fakeAsync() or done() to handle asynchronous tasks

When creating an Angular test with Jest and dealing with asynchronous operations, do you have a preference for how to handle it? it('', fakeAsync(() => { // test code here })); or would you rather use something like it('' ...

Mixing Jest and Cypress in a TypeScript environment can lead to Assertion and JestMatchers issues

When utilizing [email protected] alongside Jest, we are encountering TypeScript errors related to Assertion and JestMatchers. What is the reason for these TypeScript errors when using Jest and [email protected] in the same project? ...

Storing Buffer data in Postgres bytea using TypeORM is limited to only 10 bytes

I am encountering an issue while trying to store images in a postgres database, as only 10 bytes of data are being saved. Here is the sequence of events: Initially, I receive a base64 encoded string on my server. I then convert it into a Buffer, assign i ...

Refine specific unions by considering past values that have been used

Here's the scenario at hand: type Option = 'x' | 'y' | 'z' | 'w' type Inquiry = { query: string; choices: Option[]; defaultChoice: Option // here's where it gets tricky } I am looking to set the def ...

The Angular ng serve command seems to be malfunctioning

Whenever I try to run ng serve, I keep getting this error: module.js:540 throw err; ^ Error: Cannot find module '@angular-devkit/core' at Function.Module._resolveFilename (module.js:538:15) at Function.Module._load (module.js:46 ...

Click on a kendo-chip in Angular to copy its content

Can someone assist me in copying the content within a Kendo Chip when clicked in an Angular application? Your help is greatly appreciated. View image here ...

The Angular application is not functioning properly after running npm start, even though all the necessary packages have

Encountering a perplexing issue with my Angular application. After checking out the code on my new machine, I attempted to run my existing Angular 12 project. However, despite the application running properly in the command prompt, it is not functioning as ...

Expanding external type declarations within Typescript

I am currently working with Typescript and the ant design library. My goal is to extend an existing interface by adding a single property. To start, I imported the original interface so you can see the folder structure: import { CollapseProps } from &apo ...