There is only a singular font awesome icon that appears properly based on the conditions set by [ngClass

I'm currently developing a user profile feature that allows users to submit links to their social media accounts. Each account is represented by a clickable icon, and the selection of which icon to display is based on various conditions within [ngClass]. Here's the code snippet:

    <div *ngIf="socialMediaLinkList.length > 0" class="topic">
            <strong>can be followed on:</strong>
                <a *ngFor="let socialMediaLink of socialMediaLinkList" [href]="socialMediaLink.link">
                    <i [title]="socialMediaLink.socialMediaType" 
                    [ngClass]="{
                        'fa fa-youtube':socialMediaLink.socialMediaType === 'YOUTUBE',
                        'fa fa-facebook-official':socialMediaLink.socialMediaType === 'FACEBOOK',
                        //Different conditional classes for each social media icon...
                }"></i>
                </a> 
        <mat-divider></mat-divider>
    </div>

The issue I'm facing is that only the last icon in the condition list displays correctly, while the rest appear as uniform blocks, as shown here: https://i.sstatic.net/Dn4Cd.png. This occurs when FLICKR is randomly included in the list of social media accounts. If FLICKR is removed, all icons become blocks. Swapping conditions changes the displayed icon, but the problem persists.

I've referred to the ngClass example at and can't find any errors.

This is how the list is initialized using the SocialMediaLink class:

export class SocialMediaLink{
  constructor(public socialMediaType:string, public link: string){}
}

//Initializing social media accounts
if(this.aboutSection.socialMediaAccounts !== undefined){
    this.selectedSocialMediaAccounts = new Map<SocialMedia,string>((<any>Object).entries(this.aboutSection.socialMediaAccounts));
    this.selectedSocialMediaAccounts.forEach((link: string, socialMediaType:SocialMedia) => 
    this.socialMediaLinkList.push(new SocialMediaLink(socialMediaType.toString(), link)));
} 

If anyone has a solution to this problem, I would greatly appreciate it. Thank you.

EDIT: Font Awesome CDN link being used: @import 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css';

Answer №1

If the condition is true in your ngClass binding, it will apply the fa class. However, if the following conditions are false, it will remove it. This results in the fa class only being preserved when the last condition is true.

To ensure that the fa class is always applied, it should be set as a common class outside of the conditional ngClass binding:

<i [title]="socialMediaLink.socialMediaType" 
  class="fa" 
  [ngClass]="{
    'fa-youtube': socialMediaLink.socialMediaType === 'YOUTUBE',
    'fa-facebook-official': socialMediaLink.socialMediaType === 'FACEBOOK',
    ...
  }"></i>

For a demo, you can visit this stackblitz.


Another approach would be to include the fa class in the ngClass binding and set its condition to true like this:

<i [title]="socialMediaLink.socialMediaType" 
  [ngClass]="{
    'fa': true,
    'fa-youtube': socialMediaLink.socialMediaType === 'YOUTUBE',
    ...
  }"></i>

Answer №2

After attempting the method suggested by @ConnorsFun, I encountered some difficulties as it did not yield the desired outcome. Here is my code implementation for both approaches mentioned above (utilizing font awesome 5 and changing the prefix 'fa' to 'fas):

<i class='fas' [ngClass]="{'fa-plus': filterCategories[0]['collapse'], 'fa-minus': !filterCategories[0]['collapse']}"></i> {{filterCategories[0]['name']}}

<i [ngClass]="{'fas': true, 'fa-plus': filterCategories[0]['collapse'], 'fa-minus': !filterCategories[0]['collapse']}"></i> {{filterCategories[0]['name']}}

The objective of this code is to toggle between the icons fa-minus (when filterCategories[0]['collapse'] is false) and fa-plus (when filterCategories[0]['collapse'] is true). However, despite the efforts, the icon remains fixed at fa-minus irrespective of the value of filterCategories[0]['collapse'].

As an alternative approach, multiple i elements were used with ngIf statements. For instance:

<span *ngIf="socialMediaLink.socialMediaType === 'YOUTUBE'><i class= 'fas fa-youtube'></span>
<span *ngIf="socialMediaLink.socialMediaType === FACEBOOK><i class= 'fas fa-facebook-official'></span>

And so forth...

Although the secondary technique functions effectively, personally, I lean towards favoring the aforementioned response from @ConnonrsFan if it can be made operational.

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

Having trouble getting a Custom React Component from an external library to work with MUI styling

I am currently working with a React component that comes from a module located in the node_modules folder: type Props = { someProps: any }; export function ComponentA(props: Props) { const [value, setValue] = React.useState(""); return ( <Te ...

The JSON representation is not appearing for the newly introduced nested components

Building a nested component within another component and implementing two-way binding for dynamically added field values using the JSON pipe in the view. However, encountering an issue where the newly added values are not reflected in the JSON view. If yo ...

Angular with Leaflet and Leaflet AwesomeMarkers error: "Attempting to access 'icon' property of undefined"

I'm attempting to integrate Leaflet Awesome Markers into my Angular 10 project to incorporate Font Awesome icons in my Leaflet markers. However, I'm running into an error when trying to create a L.AwesomeMarker. https://i.sstatic.net/7o81y.png ...

Angular 2 validation issue not functioning as anticipated

Here is a validator function that I have: export const PasswordsEqualValidator = (): ValidatorFn => { return (group: FormGroup): Observable<{[key: string]: boolean}> => { const passwordCtrl: FormControl = <FormControl>group.contr ...

Explain a category of instance used in a template parameter

I am currently working on implementing a basic IOC container with type-checking capabilities. My goal is to pass the "register" method an abstract class type along with an instance of a derived type. In the "resolve" function, I aim to provide an abstrac ...

Checkboxes within Angular's reactive forms are a powerful tool for creating dynamic user

Currently, I am working on a contact form that includes checkboxes for users to select multiple options, with the requirement of selecting at least one box. My challenge lies in figuring out how to pass all the selected checkboxes' data to an API usin ...

Incorporate typings into your CDN integration

I'm interested in utilizing a CDN to access a JSON validation library, as it's expected to provide faster performance (due to retrieving the file from the nearest server within the CDN). The JSON validation library in question can be found here: ...

Trouble shooting: Angular 2 Http get request not firing

I'm facing an issue where nothing happens when I try to subscribe to my observable. There are no errors in the console or during the build process. Below is the code snippet that I am using: My service getBlueCollars(): Observable<BlueCollar[]& ...

Two services declared with "providedIn: 'root'" that have identical names

Imagine if there are two distinct services in two separate project categories, both sharing the same name. /app/services/category1/my.service.ts: @Injectable({ providedIn: 'root' }) export class MyService { foo() { return 'foo&apo ...

Angular Table Expansion Panel: Expanding Your Data in Style

Recently started exploring Angular and struggling to find a straightforward method to incorporate a table with an expansion slider containing dropdown menus. You can view the wireframe design Gif I created using Javascript by visiting this link: I came a ...

The process of building an Angular package results in the creation of if(false) {...}

I'm currently working on an Angular package repository hosted on GitHub at https://github.com/marcobuschini/parking-widget. All my tests pass successfully and there are no errors when I build using ng build. However, the resulting code contains some i ...

Is there a way to access the value or key of a JSON property in an Angular template for rendering purposes?

Having trouble displaying the JSON values of certain properties on screen. Utilizing Angular Material table to showcase my JSON response. The code snippet below is responsible for rendering the JSON data: <mat-card-content class="dashboard-card-cont ...

Navigating the complexities of integrating Rollup, ES modules, TypeScript, and JSX can be a challenging endeavor due to

Lately, I've been learning about the tools mentioned in the title. However, I've encountered some bumps along the way, so I'm turning to StackOverflow for help. My Requirements I need something like Rollup to pack my stuff For bare module ...

How can you utilize an injected service from inside a Class decorator in Typescript/NestJS?

Can an injected service be accessed from within a Class decorator? I aim to retrieve the service in the personalized constructor: function CustDec(constructor: Function) { var original = constructor; var f: any = function (...args) { // How can I ...

Angular is throwing an error stating that the property 'json' cannot be found on the type 'Object'

After updating my Angular app to version 7 and switching to httpClient, I encountered the following error: Property 'json' does not exist on type 'Object' at line let act = data.json().find(x => x.ActivityId == activityId); I sus ...

The type declaration for the Storage.prototype.setObject method

I'm facing a challenge in creating a d.ts file for the given DOM feature. Storage.prototype.setObject = function(key:string, value:any) { this.setItem(key, JSON.stringify(value)); } Storage.prototype.getObject = function(key:string) { var va ...

What is the best way to navigate back to the previous page while retaining parameters?

Is there a way to return to the previous page with specific parameters in mind? Any suggestions on how to achieve this? import {Location} from '@angular/common'; returnToPreviousPage(){ this._location.back(); } What I am looking ...

Creating an HTTP method handler function in Next.js API routes with an unspecified number of generic parameters

Looking to create a wrapper function in NextJS for API routes that can handle multiple HTTP methods with different handlers. For example, check out the TS playground interface GetResponse { hello: string, } // empty object type PostResponse = Record&l ...

The parameter 'CallHistoryMethodAction<[string, unknown?]>' does not match the 'UserActionType' parameter

Using a development environment with React, TypeScript, and connected-react-router. My Intention: I aim to utilize the router action asynchronously within the user action. After successful login, I want the application to navigate to the main screen. Err ...

Replace the content of the HTML tag in the index.html file with a different HTML file located at a specific URL in an Angular application

Currently utilizing angular universal. The primary URL being: Upon opening this URL, the function res.render('index') is triggered, leading to the rendering of the index.html file, as depicted in the following code snippet. app.get('*' ...