Leveraging Font Awesome and Material Icons within ngFor in Angular 2

I have a unique situation where I need to display a dynamic list of icons in a right side bar. These icons are added to the sidebar based on user actions and are displayed using the ngFor directive.

The challenge here is that some icons come from Font Awesome while others come from Google Material.

<!--Font Awesome-->
<i class="{{myIcon}}"></i>

<!--Material-->
<md-icon>{{myIcon}}></md-icon>
<!--Or-->
<i class="material-icon">{{myIcon}}</i>

Given that these icon classes are not interchangeable, how can we use ngFor to display both types of icons by only providing the name of the icon as a string?

Answer №1

I have the perfect solution for your problem. I recently tackled this exact issue.

Although you only inquired about the code needed between the *ngFor loop to dynamically choose and display the correct icon based on a string, I will provide a comprehensive guide including setting up Font Awesome for others who may need it.

Let's begin by ensuring that you have included the Font Awesome CSS in the header of your website. You can easily obtain a link to the CDN version from Font Awesome by visiting and adding it to your header section.

<script src="https://use.fontawesome.com/c26638a4cc.js"></script>

Next step is to create an alias for Font Awesome in your app.module file. Start off by importing the following:

import { MdIconModule, MdIconRegistry } from '@angular/material';

Don't forget to include MdIconRegistry in the list of providers.

  providers: [ 
    ...
    MdIconRegistry,
    ...
  ], 

Now, proceed to register Font Awesome with MdIconRegistry inside AppModule as shown below:

constructor(..., 
public mdIconRegistry: MdIconRegistry) {

    mdIconRegistry.registerFontClassAlias('fontawesome', 'fa');
    ...
}

With these steps completed, you can use Font Awesome icons in your application like this:

 <md-icon class="some-class" fontSet="fa" fontIcon="fa-trophy"></md-icon> 

Moving on to address the original query which involves dynamically displaying either a material design icon or a Font Awesome icon based solely on the icon's string value.

In order to accomplish this, I will rely on the convention of Font Awesome icons starting with 'fa-'. If this approach works for you, we can check for 'fa-' and set fontSet and fontIcon accordingly.

<md-list-item *ngFor="let menuitem of menuList">

<button md-button ...>
    <md-icon [fontSet]="menuitem.icon.substr(0,3) === 'fa-' ? 'fa' : ''" 
             [fontIcon]="menuitem.icon.substr(0,3) === 'fa-' ? menuitem.icon : ''" 
             [ngClass]="{'your-fa-custom-class': true }">
    <span>{{ menuitem.name }} </span>
</button>

The ngClass directive also allows the inclusion of .your-fa-custom-class where you can customize the font size specifically for Font Awesome icons.

That's all you need to do! Your setup is now complete!

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

Conceal a table with jQuery

Is there a way to initially conceal a table on page load only to reveal it with a sliding animation when a specific link is clicked? I have attempted using the following code to hide the table: $('.table_div').hide(); I have enclosed the table ...

Ensure that the main div remains centered on the page even when the window size is adjusted

Here is the code snippet: <div id="root"> <div id="child1">xxxx</div> <div id="child2">yyyy</div> </div> CSS : #root{ width: 86%; margin: 0 auto; } #root div { width: 50%; float: left; border: ...

Remove the unnecessary space at the bottom of the Mat Dialog

I'm currently utilizing Angular Material within my Angular application. One issue I am facing is the excessive whitespace at the bottom of a dialog that displays information about a post. How can I reduce or eliminate this unnecessary space? Take a l ...

Vue application experiencing issues with applying Sweet Alert CSS styles

I successfully integrated vue-sweetalert2 into my Vue app (version 2.6). The setup in my main.js file looks like this: import VueSweetalert2 from 'vue-sweetalert2'; Vue.use(VueSweetalert2); In one of my components, I have a basic button with a ...

Is it feasible to access and modify local files within an Angular project using TypeScript code in the angular component.ts file? If so, how can this be achieved?

My Angular application is built on version 4 or higher. I have a setup in my project where there is a folder containing a txt file and another folder next to it with an angular component.ts file: FolderWithFile -----file.txt ComponentFolder -----person.co ...

Notification with jQuery

I am looking to display an alert message when val = -1. However, the issue I am facing is that this message always appears at the bottom of the page regardless of the value of val. if ($val == -1) echo ' <script> $( ...

Utilizing Angular 6 mergeMap for handling nested API requests

My goal is to retrieve a list of clients along with their accounts using the observe/subscribe pattern. Each client should have a list of their accounts associated with their client id. This is how I attempted it: this.httpService.getClients().subscribe( ...

Can you choose the class that has not yet been seen before?

Imagine a scenario where the following code is present: <div class="a"> <div>1</div> <div>2</div> <div> <div> <div class="b">3</div> </div> ...

Issues with Angular 2 template not refreshing during testing

I'm struggling to get this to function properly. it('should have the expected <h1> text', async(() => { let fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const sectionEl = fixture.debugElement.que ...

Printing content from an Angular dashboard can be achieved by following a few

Currently, I am working on developing a legal document automation program for my company. However, I have encountered an issue during the final stages of completing this web application. For the layout and setup, I am using the default angular Dashboard l ...

Angular-CLI personalized schematics and collections

I am currently in the process of creating custom schematics for Angular CLI. After some experimentation, I have discovered that the "collection" needs to be compiled because the CLI cannot read TypeScript directly. This means that you can't simply clo ...

The Bootstrap DateTimePicker is displaying on the screen in an inaccurate

I'm having an issue with the datetimepicker on my project. The calendar appears incorrectly in Chrome, but looks fine in Edge. Here's a screenshot from Chrome: https://i.stack.imgur.com/Hi0j4.png And here is how it looks in Edge: https://i.stac ...

HTML Scroll Blocking

Recently, I have been working on designing the mobile version of a website. However, I noticed that when I try to scroll quickly on my phone, the scrolling gets interrupted and I have to wait for it to catch up. I am using the fullpage.js library in this ...

JHipster's selection of radio button options

Within a jhipster project, I have an Enumeration field containing values "A, B, C, D, E". The conventional approach in Jhipster utilizes a Select/Options setup: <div class="form-group"> <label class="form-control-label" jhiT ...

When using setInterval, the image remains static on Safari but updates on Chrome

In my project, I am using a mock array to distribute data. One part of the project utilizes this data to display a list of cases, each with assigned images. When a case is hovered over, the images associated with that case are displayed one at a time, with ...

Enhance your Vue app by dynamically modifying classes with Tailwind

I am working on a Vue3 application that utilizes Tailwinds configured in the tailwind.config.js file. My question is, can I dynamically modify the value of a preconfigured class from the tailwind.config.js file? For instance: tailwind.config.js: const d ...

Protractor performs the afterEach function prior to the expectations being met

I am completely baffled by the behavior of this code. Everything seems to be executing correctly up until the 'expect' statement, at which point it abruptly navigates to a new page and runs the afterEach function. I've tried various solution ...

Is there a way for me to attach a link to a picture displayed in a lightbox that directs to an external ".html" file?

I have a platform where users can view images in a gallery and when they click on an image, it opens up in a lightbox. I am trying to add a feature where the opened image can be clicked again to redirect the user to an external page. I attempted to nest t ...

Ways to trigger an event based on the outcome of a pop-up window

In my current project, I am working on a component that includes three buttons: two default options and an additional modal dialog option for more advanced choices. When one of the default buttons is clicked, the component emits an event based on the selec ...

Discover the technique of accessing HTML/CSS toggle switch value in Golang

I am attempting to incorporate a toggle switch into my webpage. I followed this specific tutorial for guidance: w3schools.com Currently, I have set up my HTML file with a button and the toggle switch. Additionally, I configured my web server in Go to lis ...