Home > database >  Passing variable into icon for Font Awesome not working
Passing variable into icon for Font Awesome not working

Time:04-29

I am using Font Awesome with Angular.

I want to loop through some data via *ngFor to create icons in a navigation bar. However, the [icon] is not accepting the values from the variable.

Component HTML


  <div  [ngClass] = "expanded ? 'navbar-collapsed': ''">
  <div >
    <button  (click)="toggleCollapsed()">
      A
    </button>
    <div  *ngIf="expanded">My Site</div>
  </div>
  <ul >
    <li  *ngFor="let data of navData">
      <a  [routerLink]="[data.routeLink]">

      //works
        <fa-icon [icon]="['fas','star']"></fa-icon> 

      //Error: Type 'string' is not assignable to type 'IconProp'.
        <fa-icon [icon]="data.iconfull"></fa-icon> 

      // Type 'string' is not assignable to type 'IconProp'.
        <fa-icon [icon]="[data.iconfirst,data.iconsecond]"></fa-icon> 

        <span  *ngIf="expanded">{{data.label}}</span>
      </a>
    </li>
  </ul>
</div>

Data

export const navbarData = [
    {
        routeLink: 'dashboard',
        iconfirst: 'fas',
        iconsecond: 'star',
        iconfull: "['fas','star']",
        label: 'Dashboard'
    }
]

CodePudding user response:

Cannot reproduce the third scenario.

From IconProp,

export type IconProp = IconName | [IconPrefix, IconName] | IconLookup;

Hence, for the second scenario,

Specify the navbarData type as:

import {
  IconProp,
  IconPrefix,
  IconName,
} from '@fortawesome/fontawesome-svg-core';

navbarData: {
  routeLink: string;
  iconfirst: IconPrefix;
  iconsecond: IconName;
  iconfull: IconProp;
  label: string;
}[] = [
  {
    routeLink: 'dashboard',
    iconfirst: 'fas',
    iconsecond: 'star',
    iconfull: ['fas', 'star'],
    label: 'Dashboard',
  },
];

Sample Demo on StackBlitz

  • Related