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

Is it possible to conduct a feature test to verify the limitations of HTML5 audio on

Is there a way to detect if volume control of HTML5 audio elements is possible on iOS devices? I want to remove UI elements related to the volume if it's not alterable. After referring to: http://developer.apple.com/library/safari/#documentation/Aud ...

What is the best approach to managing exceptions consistently across all Angular 2/ Typescript observables?

Throughout the learning process of Angular2, I have noticed that exceptions are often caught right at the point of the call. For example: getHeroes(): Promise<Hero[]> { return this.http.get(this.heroesUrl) .toPromise() ...

Embedded video player is failing to display and play the video file

Currently, I am in the process of developing a PHP backend for my mobile application. One specific requirement involves displaying and playing a video file that is hosted. This is the approach I have taken: $data[$i]['video'] = '<vide ...

Steps for deactivating a button until the form has been submitted

Click here for the Fiddle and code sample: $(".addtowatchlistform").submit(function(e) { var data = $(this).serialize(); var url = $(this).attr("action"); var form = $(this); // Additional line $.post(url, data, function(data) { try { ...

Only conceal the table column if space is limited

A scenario involves an HTML table with two columns that need to be displayed fully, with the second column aligned to the right. Currently, this has been achieved by setting the width of the first column to 100%. However, a challenge arises where the words ...

What is the best way to center an image and text vertically using bootstrap?

I'm currently working on a Bootstrap website and have reached a section where I want to display text on the left and an image on the right. While I've managed to achieve this layout, I'm struggling with vertically centering the image. Despit ...

Using AJAX to send data with a POST request in Django may not function properly

Let me preface by saying I have searched for solutions online, but none of them seem to address my specific issue (mainly because they use outdated methods like Jason). I am currently working on a Django project and trying to implement ajax for a particul ...

A guide to resolving the Angular 11 error of exceeding the maximum call stack size

I am currently working with 2 modules in Angular 11 CustomerModule AccountingModule I have declared certain components as widget components in these modules that are used interchangeably: CustomerModule -> CustomerBlockInfoWidget AccountingModule -&g ...

Eliminating the appearance of horizontal scroll bar by employing transform scale to zoom out

When you run the code provided in the link below and scale down the HTML to 50% while increasing the width to fit the window, a scrollbar becomes visible. This only occurs in Chrome and not in Firefox. Click here The content of the DOM can be modified and ...

Is there a method or API available for interacting with an <object> that is currently displaying a video?

Yay, I figured it out! I've been using video.js to play videos on a website that needs to work offline too. Unfortunately, using flash is not an option due to compatibility issues. So, I decided to write my own fallback solution. For Internet Explor ...

"Encountering the error message "Uncaught TypeError: $(...).summernote is not a function" while working with

I've encountered an issue while trying to implement summernote into my Angular app. I keep receiving the error message "$(...).summernote is not a function" and it seems like summernote is not loading properly on the page. I'm unsure of what step ...

What is the best way to update typings.json and typing files?

Here is the structure of my typings.json: { "globalDependencies": { "aws-sdk": "registry:dt/aws-sdk#0.0.0+20160606153210" }, "dependencies": { "lodash": "registry:npm/lodash#4.0.0+20160416211519" } } Currently, I find it tedious to update ...

Unable to append HTML table row to designated table

I am trying to populate an HTML table with the JSON string data I receive. The object data seems correct, but for some reason, it is not getting appended to the table. Can you help me identify what's wrong with my jQuery append statement? functio ...

The conflict name has an impact on both the folder and the PHP file

Within my web directory, there exists a folder titled area-nursing that houses various PHP files along with a specific file named area_nursing.php. However, upon attempting to rewrite area_nursing.php as area-nursing using the .htaccess file, I encounter ...

Transitioning in CSS involves animating the changing of a CSS property over

My goal with CSS is to create a transition effect with a delay that behaves differently when entering and exiting. Specifically, I want a 1 second delay when an element enters, but no delay (0 seconds) when it exits. transition: width 0.3s ease-in 1s; tra ...

I have set up a custom ag-grid three times within a single component, however, only the first instance is properly initialized while the other two instances are not initialized

I have developed a custom ag-grid for reusability in my project. Initially, when I initialize the custom ag-grid in one component, it works perfectly as shown below: example.html <html> <body> <input type="text"> <md-app-aggrid [c ...

Mandatory tick box needed for submitting PHP form

Although the topic of PHP form validation is frequently discussed, I am a complete beginner in PHP and I am currently experimenting with a PHP form script that I discovered here. As a result, I am unsure about how to proceed with incorporating two specific ...

The fine balance between a horizontal <img> and a <div> element

Can't seem to get rid of the thin white line between a black image and a div with a black background on a page where the body background is set to white. I've tried setting border: 0 !important among other things, but it just won't go away. ...

Can you tell me about the interface type format used in the angular cli?

I found myself feeling disoriented while reading the documentation. ng generate interface <name> <type> There was ambiguity on what to input for the type field. Is it supposed to be a string, object, array, or can I define properties like ema ...

A straightforward development and production build to incorporate HTTPS for a static website created with React and Express

Is there a straightforward method to create a static web page and Node backend where the Node server runs in HTTPS during development but not in production? How can the static web page point to https://localhost/foo in dev mode, and simply /foo in producti ...