Using Angular 2: Applying a specific class to a single element with [ngClass]

I have a header table with arrows indicating sorting order, using Bootstrap icons. However, when I click on a column, all columns receive the icon class. Here is an example of what I mean: https://i.sstatic.net/CAS81.png

Below is the code snippet:

HTML ->

<table class="table table-hover">
<thead>
    <th (click)="orderBy('username')">Username<span [ngClass]="displayArrow()"></span></th>
    <th (click)="orderBy('email')">Email<span [ngClass]="displayArrow()"></span></th>
    <th (click)="orderBy('id')">Id<span [ngClass]="displayArrow()"></span></th>
    <th (click)="orderBy('roleId')">Role Id<span [ngClass]="displayArrow()"></span></th>
</thead>
<tbody>
    <tr *ngFor="let user of usersListData | orderByController: OrderByParams">
        <td (click)="onSelectFilterParam(user.username)">{{user.username}}</td>
        <td (click)="onSelectFilterParam(user.email)">{{user.email}}</td>
        <td (click)="onSelectFilterParam(user.id)">{{user.id}}</td>
        <td (click)="onSelectFilterParam(user.roleId)">{{user.roleId}}</td>
    </tr>
</tbody>

AppComponent ->

private toggleArrow = 0;

orderBy(columnName: string) {
    this.toggleArrow++;
    if(this.toggleArrow > 2) {
        this.toggleArrow = 0;
    }
    console.log(this.toggleArrow);
}

displayArrow() {
    if(this.toggleArrow === 0) {
        return '';
    }
    else if(this.toggleArrow === 1) {
        return 'glyphicon glyphicon-chevron-up';
    }
    else if(this.toggleArrow === 2) {
        return 'glyphicon glyphicon-chevron-down';
    }
}

Is it possible to bind the class to just one element?

Answer №1

This approach may not be the most sophisticated, but you can achieve something similar by specifying the columns in your component.

   columns: any[] = [
      {'Name':'username','Direction':0},
      {'Name':'email','Direction':0},
      {'Name':'id','Direction':0},
      {'Name':'roleId','Direction':0}
    ]

In your HTML template, you can implement it like this:

<table class="table table-hover">
<thead>
    <th *ngFor="let col of columns" (click)="orderBy(col.Direction)">{{ col.Name }}<span [ngClass]="displayArrow(col.Direction)"></span></th>
</thead>
<tbody>
    <tr *ngFor="let user of usersListData | orderByController: OrderByParams">
        <td (click)="onSelectFilterParam(user.username)">{{user.username}}</td>
        <td (click)="onSelectFilterParam(user.email)">{{user.email}}</td>
        <td (click)="onSelectFilterParam(user.id)">{{user.id}}</td>
        <td (click)="onSelectFilterParam(user.roleId)">{{user.roleId}}</td>
    </tr>
</tbody>

The function for ordering would look like this:

orderBy(dir: number) {
    dir++;
    if(dir > 2) {
        dir = 0;
    }
    console.log(dir);
}

And for displaying the arrow icon:

displayArrow(dir: number): string {
    if(dir === 0) {
        return '';
    }
    else if(dir === 1) {
        return 'glyphicon glyphicon-chevron-up';
    }
    else if(dir === 2) {
        return 'glyphicon glyphicon-chevron-down';
    }
}

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

What's causing the "* before initialization" error in Vue with TypeScript?

I am encountering an issue with my code where I get the error "Cannot access 'AuthCallback' before initialization" when attempting to call the router function in the AuthCallback component. What could be causing this problem? The desired function ...

Accessing images hosted on an IIS server from a client using a URL in an ASP .Net application

My application is built using Api ASP.Net, and I store the images in the "wwwroot" directory Content https://i.sstatic.net/JP2Lx.png After publishing my application, the folder structure remains intact and I need to be able to access the images through ...

What is the best way to provide inputs to a personalized validation function?

I am seeking a solution to pass an array of prefix strings to my custom validator in order to validate that the value begins with one of the specified prefixes. Below is the code snippet for my current validator: @ValidatorConstraint({ name: 'prefixVa ...

Using Angular to automatically update the user interface by reflecting changes made in the child component back to the parent component

Within Angular 5, I am utilizing an *IF-else statement to determine if the authorization value is true. If it is true, then template 2 should be rendered; if false, then template 1 should be rendered. Below is the code snippet: <div *ngIf="authorized; ...

Using Bootstrap 3 with ResponsiveSlides.js

I've been struggling to center the ResponsiveSlides slider within a bootstrap column. Despite resizing my large images to 80% in the CSS, they still refuse to align properly since they're no longer fitting the entire screen at 100%. Can someone l ...

Issues with animations in Ionic 3 and Angular 4 not functioning as expected

Working on a component to animate an accordion list, I made all the necessary changes such as importing import { BrowserModule } from "@angular/platform-browser"; and import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; as well ...

Tips for locating the beginning and conclusion of a RxJS.ajax request?

I'm utilizing the RxJS.ajax call to verify the availability of a product in the database. The response from this call typically takes between 2 to 4 seconds. During that retrieval time, I would like to show a message indicating "searching for product" ...

Clearing the require cache in Node.js using TypeScript

I need to repeatedly require a module in TypeScript and Node for testing purposes. I came across an approach on this post which suggests the following code snippet: const config = require('./foo'); delete require.cache[require.resolve('./fo ...

Effect fails to activate on the third occurrence of the action

After successfully running on the first two action dispatches, the effects fail to trigger on the third time. I have tried the solutions provided in this thread and here, but none of them work for me. Here is the relevant code snippet: @Effect() get ...

What is the best way to import a typescript file using a provided string?

I have a directory filled with JSON schemas, all coded in TypeScript. My goal is to import them collectively while preserving the typing, instead of having to write out numerous import statements. These schemas are utilized for validating JSON data being ...

How to deactivate Kendo Dropdownlist in Angular 2

Currently, I am attempting to disable a kendo-dropdownlist (named ddlChargeType). The goal is to prevent the user from manually selecting a value, while still allowing for programmatic selection (such as when a valid option is chosen in another dropdown, ...

Angular 5 arrays within arrays

I'm currently facing an issue with using ngFor on a nested JSON output. The outer loop is working as expected, but the inner loop is not functioning properly. Below is my code snippet: Typescript file import { Component, OnInit } from '@angula ...

TypeScript: The capability to deduce or derive values for a type from a constant object literal that is nested with non-distinct keys

I'm trying to figure out a way to utilize TS/IDE to display specific literal values from a style guide object, instead of just the inferred type. Here's an example: const guide = { colors: { black: { medium: "#000000", } ...

Exploring nested contexts in react testing library with renderHook

This is a sample code snippet in TypeScript that uses React and Testing Library: import React, { FC, useEffect, useMemo, useState } from 'react'; import { renderHook, waitFor } from '@testing-library/react'; interface PropsCtx { inpu ...

Having issues with Bootstrap customization in an Angular 7 project

I am currently working on customizing a Bootstrap 4 theme within an Angular 7 project. After installing Bootstrap, I updated my angular .json file to include the following: "styles": [ "./node_modules/@angular/material/prebuilt-themes/de ...

Integrating Angular 2 with Java functionalities and JSP

Starting my journey with the Angular 2 framework, I recently dove into working with it. As I delved deeper, many questions began to surface. My initial step was creating an Angular project using the Angular CLI, which went smoothly. However, when I attem ...

Is there a way to switch an input's appearance to resemble that of a label?

Looking to customize my input fields to resemble labels at first, then apply editable styles with angular.js upon button click. Utilizing bootstrap for my project, wondering if there is a built-in class that can be toggled on and off for these inputs? ...

The TypeScript 'object' type

My query regarding the definition of TypeScript's {} type has brought about some confusion. Initially, I believed it represented an "empty object with no properties," but I recently encountered an ESLint rule that prohibits the use of {} type because ...

"Receiving HTML response from an HTTP GET request in Angular 2

Attempting to transmit test data from my node.js server to the front end. router.get('/abc', (req, res) => { return res.json({ test: "success!" }); }); In my service component: private url = "http://localhost:4200/auth/abc"; getTitl ...

What could be causing the error message (No overload matches this call) to pop up when attempting to subscribe to .valueChanges() in order to retrieve data from Firestore?

Currently, I am developing an Angular application that utilizes Firebase Firestore database through the angularfire2 library. However, I am encountering a challenge. I must admit that my background is more in Java than TypeScript, so there might be some g ...