Client-side condition handling in Angular 2

How can I change the icon image on a block/unblock button based on the user's active status? For example, showing an unlock image when the user is active and vice versa.

Image

https://i.stack.imgur.com/aM0ff.png

Html

<link href="../../font-awesome-4.6.3/css/font-awesome.min.css" rel="stylesheet" />
<h1>User View </h1>

<div class="row">
    <div class="panel panel-default">
        <div class="table-responsive">
            <table class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th class="text-center">First Name</th>
                        <th class="text-center">Last Name</th>
                        <th class="text-center">Email</th>
                        <th class="text-center">Status</th>
                        <th class="text-center">Block/Unblock</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let user of _data | paginate: { itemsPerPage: 10, currentPage: p }">
                        <th>{{user.FirstName}}</th>
                        <th>{{user.LastName}}</th>
                        <th>{{user.Email}}</th>
                        <th>{{ user.IsActive == true ? 'Active' : 'Block' }}</th>
                        <th>
                            <div class="text-center">
                                <button type="button" class="btn btn-xs " (click)="approvalPendingRequest(user.SubscriptionId)">
                                    <i class="fa fa-unlock" aria-hidden="true"></i>
                                </button>
                            </div>
                        </th>

                    </tr>
                </tbody>
            </table>
            <pagination-controls (pageChange)="p = $event" #api></pagination-controls>

        </div>
    </div>
</div>

Answer №1

If you're looking to achieve this, consider using the ngClass directive:

<button type="button" class="btn btn-sm " (click)="processPending(user.id)">
    <i [ngClass]="['fa', user.active ? 'fa-lock' : 'fa-unlock']" aria-hidden="true"></i>
</button>

Answer №2

Fix It Fast

Replace class="fa fa-unlock" with

class="fa {{ user.IsActive == true ? 'fa-lock' : 'fa-unlock' }}"

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 role does the empty object type {} play in typescript?

In the @types/React package of the DefinitelyTyped library, I came across this definition: interface FunctionComponent<P = {}> { (props: PropsWithChildren<P>, context?: any): ReactElement | null; propTypes?: WeakValidationMap&l ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

Priority is given to strings over numbers

Here's some code I'm working with: <tbody> <tr> <td class="float-left"> <!-- {{selectedTemplat?.modifiedAt | da ...

What are the solutions for handling undefined data within the scope of Typescript?

I am encountering an issue with my ngOnInit() method. The method fills a data list at the beginning and contains two different logic branches depending on whether there is a query param present (navigating back to the page) or it's the first opening o ...

When using Angular 4 CanActivate guard in conjunction with a service, the component may not load properly. However, by simply using Observable

When attempting to implement the CanActivate guard in Angular, I encountered an issue where it didn't work when calling a service and using return true, or even return Observable.of(true);. However, the guard did work and the component loaded success ...

Retrieving the checked value of a checkbox in Angular instead of a boolean value

Currently I am working on a project using ServiceNow and AngularJS. I am having trouble obtaining the value of a checkbox. Here is the code snippet: $scope.userFavourite = function(favourite){ alert(favourite); } <labe for="tea"& ...

Encountering an "Unexpected token" error when importing a JSON file in TypeScript even though the JSON is valid

I recently read an article on Hacker Noon about importing JSON into TypeScript, and decided to give it a try in my code. Here's the import line I used: import data from './assets/fonts/helvetiker_bold.typeface.json'; To test if the import ...

Creating a setup in TypeScript to enable imports between CommonJS and ES modules (for node-fetch and Express)

I'm facing a challenge in trying to integrate two libraries into a single project: fetch-node, an ES module, and Express, which follows the CommonJS format. The issue arises from needing to import fetch-node using: import fetch from 'node-fetch&a ...

Executing asynchronous functions in Angular 2

In my Angular demo.ts file, I have included two functions fetchTables() and fetchAllTables() inside the constructor of a class. Both functions make API calls. However, I am facing an issue where one of the calls fails consistently. Sometimes fetchTables() ...

Display a modal dialog using HttpInterceptor

@Injectable() export class MyInterceptor implements HttpInterceptor { intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> { //display a modal dialog to wait for user response before proceeding with t ...

Encountering issues with package resolution in VS Code while setting up a monorepo with yarn workspaces, Vite, React, and

I recently set up a monorepo using yarn@3 workspaces. Here is the structure of my root package.json: { "name": "hello-yarn-workspaces", "packageManager": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Resolving "Module not found: Error: Can't resolve 'url'" issue in Angular 14 while invoking web3 smart contract function

How do I resolve the web3-related errors in my Angular 14 dapp? I attempted to fix the issue by running npm i crypto, npm i http, and more. Every time I try to call a function from a smart contract with code like this.manager = await report.methods.mana ...

There was an issue with Angular 2.0 at :0:0, which was caused by a response with status: 0 from the URL: null

I am a beginner in Angular 2.0 and I am currently working on creating a sample application using @angular\cli. To serve the application on my local machine, I use the command ng serve --open, which opens it at localhost:4200. Now, I have developed a ...

Beginner's Guide: Building your debut JavaScript/TypeScript library on GitHub and npm

I am looking to develop a simple JavaScript/TypeScript library focused on color conversion. Some of the functions and types I aim to export include: export type HEX = string; export type RGB = { r: number; g: number; b: number }; export type RGBA = { r: n ...

Creating Angular components and attaching them to the body tag is a simple yet

My goal is to create a component at the root element of the page. I have come across some resources that are similar to what I need, but they use the DynamicComponentLoader which is now considered deprecated. public component: any; constructor( public ...

Utilize existing *.resx translation files within a hybrid application combining AngularJS and Angular 5

Greetings! I currently have an AngularJS application that utilizes $translateProvider for internalization and WebResources.resx files: angular.module('app') .config(['$translateProvider', 'sysSettings', 'ngDialogProv ...

Looking to verify the functionality of the router.navigate method when employing relativeTo?

How can we effectively test the router.navigate method to ensure it accepts provided queryParams and navigates to the correct location path? In Component file:-- syncQueryParams() { this.router.navigate([], { relativeTo: this.activatedRoute, ...

When the form is submitted, the HTMLCollection becomes void

I am facing an issue with a form that always seems to be invalid. To troubleshoot, I tried running this command in my web browser to identify the invalid fields: document.getElementsByClassName('ng-invalid'); However, the HTMLCollection returned ...

How to ensure Angular mat-button-toggle elements are perfectly aligned within their respective groups

https://i.stack.imgur.com/Wjtn5.png Hello there, I'm trying to make the numbers in the first group match the style of the second group (noche, mañana...). I've set both the group and individual element width to 100%, but the numbers beyond 22 ...

How can a TypeScript function be used to retrieve a string (or JSON object)?

When attempting to retrieve data from a web API using TypeScript and return the JSON object, encountering an error has left me puzzled. Inside my function, I can successfully display the fetched data on the console, but when I try to return it with return ...