Incorporate FontAwesome icons into table headers within an Angular framework

I am attempting to customize the icons for sorting in my table headers by following the guidelines laid out in the ng-bootstrap table tutorial.

The NgbdSortableHeader directive plays a key role in changing the sorting of columns:

@Directive({
  selector: 'th[sortable]',
  host: {
    '[class.asc]': 'direction === "asc"',
    '[class.desc]': 'direction === "desc"',
    '(click)': 'rotate()'
  }
})
export class NgbdSortableHeader {
  @Input() sortable: string = '';
  @Input() direction: SortDirection = '';
  @Output() sort = new EventEmitter<SortEvent>();

  rotate() {
    this.direction = rotate[this.direction];
    this.sort.emit({column: this.sortable, direction: this.direction});
  }
}

In addition, here is the component containing the table:

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss'],
  providers: [UserService]
})
export class UsersComponent implements OnInit {
  faSort = faSort;
  faSortUp = faSortUp;
  faSortDown = faSortDown;

  users$: Observable<User[]>;
  total$: Observable<number>;

  @ViewChildren(NgbdSortableHeader) headers!: QueryList<NgbdSortableHeader>;

  constructor() {
  }

  ngOnInit(): void {
  }

  onSort({column, direction}: SortEvent) {
    // reset other headers
    this.headers.forEach(header => {
      if (header.sortable !== column) {
        header.direction = '';
      }
    });

    this.service.sortColumn = column;
    this.service.sortDirection = direction;
  }
}

I am curious about ways to retrieve the current column sorting order and dynamically change or hide the associated icons.

<th scope="col" sortable="firstName" (sort)="onSort($event)">
  Name
  <fa-icon [icon]="faSort"></fa-icon>
  <fa-icon [icon]="faSortUp"></fa-icon>
  <fa-icon [icon]="faSortDown"></fa-icon>
</th>

Answer №1

Utilizing the @ChildComponent in the sort directive resolved my problem effectively:

<th scope="col" sortable="firstName" (sort)="onSort($event)">
  Name
  <fa-icon [icon]="faSort" size="lg"></fa-icon>
</th>
import { Directive, EventEmitter, Input, Output, ViewChild, ContentChild, ElementRef } from "@angular/core";
import { FaIconComponent } from "@fortawesome/angular-fontawesome";
import { faSort, faSortUp, faSortDown } from "@fortawesome/pro-regular-svg-icons";

export type SortDirection = 'asc' | 'desc' | '';
const rotate: {[key: string]: SortDirection} = { 'asc': 'desc', 'desc': '', '': 'asc' };

export interface SortEvent {
  column: string;
  direction: SortDirection;
}

@Directive({
  selector: 'th[sortable]',
  host: {
    '[class.asc]': 'direction === "asc"',
    '[class.desc]': 'direction === "desc"',
    '(click)': 'rotate()'
  }
})
export class NgbdSortableHeader {
  @Input() sortable: string = '';
  @Input() direction: SortDirection = '';
  @Output() sort = new EventEmitter<SortEvent>();

  @ContentChild(FaIconComponent) sortIcon?: FaIconComponent;

  rotate() {
    this.direction = rotate[this.direction];
    this.sort.emit({column: this.sortable, direction: this.direction});

    if (this.sortIcon !== undefined)
    {
        this.sortIcon.icon = this.direction === 'asc' ? faSortDown : this.direction === 'desc' ? faSortUp : faSort;
        this.sortIcon.render();
    }
  }
}

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

When hovering over items in the navigation bar, the entire bar expands seamlessly

I've spent countless hours trying to troubleshoot an issue with my dropdown menu that expands whenever I hover over it. The bar stretches out to accommodate the list of dropdown contents and then reverts back to normal when I move my cursor away. My a ...

converting HTML values to TypeScript

I'm a beginner with Angular and could use some assistance. Currently, I have two components - one for the index and another for navigation. Within the index component, there are subcomponents that change based on the value of a variable called produ ...

Issue encountered: Inoperable binding when employing ko.mapping with two distinct models

I've been struggling to implement a drop-down select in conjunction with a table on a page using knockout bindings. The issue arises when I try to use the mapping options in the knockout binding plugin – either the drop-down or the table behaves inc ...

Tips for styling Ajax.ActionLink elements with CSS

Hi there, I'm trying to style a navigation bar using CSS. I'm pulling the navigation bar values from a database using Ajax.ActionLink. I attempted to use JavaScript but encountered an error stating "jQuery is not defined", Here's the cod ...

npm encountered an error while trying to fetch the requested package when running ng new app

I'm working on developing a new application using the ng new app command. Everything goes smoothly until reaching the final CREATE message below. At that point, it gets stuck for hours (literally) at the "Installing packages (npm)..." stage. Eventu ...

Steps for breaking down a given string into divisions that correspond to an A4 sheet

Within my content, there are various styles applied. For example: This is a <b>bolded</b> word. I am seeking a solution to divide this long string into smaller sections that would fit on an A4 page accurately. The goal is to maintain the integ ...

Display movie details in a responsive column layout that condenses into a single column

I'm having trouble displaying movie information on a website due to CSS and HTML issues. My goal is to align the title (Director:, Cast:, etc) with the first item in the list, and have all subsequent items follow below. I initially tried using a defin ...

`Is there a way to manipulate the timer in JavaScript?`

My current project involves creating a timer in minutes and seconds. The user inputs the desired time in minutes into a textbox named "textbox2". However, when I attempt to retrieve the value of this input using `getElementById.value`, it returns a NULL er ...

Is there a way for me to access the response from the PHP file I'm calling with Ajax?

I am just starting to explore ajax and jquery, and I recently found a code online that I'm tweaking for my own use. However, I am struggling with how to handle responses from PHP in this context. The current setup involves ajax POSTing to a php page ...

How can I toggle the visibility of a div based on whether a variable is defined or not?

How can I display a specific div on my webpage only when certain variables in PHP pull out a specific result from a database? I attempted to use the code snippet below, but it's not working as expected. Can someone provide guidance on how to achieve ...

Unexpected disconnection from Socket.io server

Utilizing node.js service and angular client with socket.io for extended duration http requests. Service: export const socketArray: SocketIO.Socket[] = []; export let socketMapping: {[socketId: string]: number} = {}; const socketRegister: hapi.Plugin< ...

Unleashing the power of ::ng-deep to access CSS in an Angular child component

I'm attempting to modify the CSS class of a child component by using ::ng-deep. Despite my efforts with various iterations of the code provided below, I have been unsuccessful in accessing the CSS. The structure of the HTML component is depicted in th ...

Determine the total of the final column in recently added rows by utilizing JavaScript

I have a table where users can dynamically add rows as needed. I am looking to implement a feature that will display the total of the last column in a text box underneath the table using JavaScript. If real-time calculations are not feasible, then I am ope ...

Issues with the performance of the Responsive Image Slider

Having trouble with the carousel on my website. The Navigation Bar is working, but the image slider isn't showing up despite trying multiple approaches. Bootstrap is properly linked and I've read through the documentation for the Bootstrap Carous ...

Convert the background image (specified in the CSS with background-image) into a PHP variable

I am looking to create a product gallery featuring 5 products, each with its own background image attribute. I am using a loop to insert the product images and I want each loop to display a different background-image. One approach I have considered is usi ...

As you scroll, the top block in each of the three columns will remain fixed within its

I need assistance with a problem involving three columns and multiple blocks within each column. Specifically, I want the first block in each column to remain fixed at the top when scrolling. However, once you reach the bottom of each column, the first blo ...

Guide to making control bar fade out when video is paused on video.js

Is there a way for the control bar to automatically disappear when the video is paused? Thank you in advance! ...

Tips for fixing a GET 404 (not found) error in a MEAN stack application

While working on a profile page, I encountered an error when trying to fetch user details of the logged-in user: GET http://localhost:3000/users/undefined 404 (Not Found) error_handler.js:54 EXCEPTION: Response with status: 404 Not Found for URL: http:// ...

Creating a Timeless Banner with the Magic of `background:url()`

I have a banner placed within a div tag that displays my banner image. I am trying to create a fading effect when transitioning to the next image, but I am struggling to achieve this. I attempted to use jQuery fadeIn(), however, it did not work as expected ...

Tips for transferring a value from a function in ASPX to a CS file

I seem to be overlooking a small detail. I have a dropdown list (DDL) and a function in my C# file. I want to pass the 'value attribute' of a selected DDL option to my function, but I can't seem to retrieve the value attribute. I checked the ...