Global configuration service for setting default behaviors, icon prefixes, fallback icons, and CSS injection settings. The configuration service allows customizing Angular FontAwesome behavior across the entire application.
Injectable configuration service providing global settings for FontAwesome components.
@Injectable({ providedIn: 'root' })
class FaConfig {
/**
* Default prefix to use when icon name is specified without prefix
* @default 'fas'
*/
defaultPrefix: IconPrefix;
/**
* Fallback icon to display when requested icon is missing
* When null, components throw error for missing icons
* When set, provides graceful fallback behavior
* @default null
*/
fallbackIcon: IconDefinition | null;
/**
* Set icons to same fixed width for alignment
* @default undefined
*/
fixedWidth?: boolean;
/**
* Automatically inject Font Awesome CSS into document
* For most cases, automatic CSS injection is sufficient
* Disable only when managing CSS manually
* @default true
*/
autoAddCss: boolean;
}import { Component } from '@angular/core';
import { FaConfig } from '@fortawesome/angular-fontawesome';
import { faExclamationTriangle } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'app-root',
template: `
<!-- These will use 'far' as default prefix -->
<fa-icon icon="heart"></fa-icon>
<fa-icon icon="star"></fa-icon>
<!-- This will show fallback icon if 'missing-icon' doesn't exist -->
<fa-icon icon="missing-icon"></fa-icon>
`
})
export class AppComponent {
constructor(config: FaConfig) {
// Set default prefix to regular icons
config.defaultPrefix = 'far';
// Set fallback icon for missing icons
config.fallbackIcon = faExclamationTriangle;
// Enable fixed width for all icons
config.fixedWidth = true;
// Keep auto CSS injection enabled (default)
config.autoAddCss = true;
}
}Recommended approach for setting application-wide configuration.
import { NgModule } from '@angular/core';
import { FontAwesomeModule, FaConfig } from '@fortawesome/angular-fontawesome';
import { faQuestionCircle } from '@fortawesome/free-solid-svg-icons';
@NgModule({
imports: [FontAwesomeModule],
providers: [
{
provide: 'FA_CONFIG',
useFactory: (config: FaConfig) => {
// Application-wide configuration
config.defaultPrefix = 'fas';
config.fallbackIcon = faQuestionCircle;
config.fixedWidth = false;
config.autoAddCss = true;
return config;
},
deps: [FaConfig]
}
]
})
export class AppModule {}Different settings for development and production environments.
import { environment } from '../environments/environment';
import { FaConfig } from '@fortawesome/angular-fontawesome';
import {
faExclamationTriangle,
faQuestionCircle
} from '@fortawesome/free-solid-svg-icons';
@Injectable()
export class FontAwesomeConfigService {
constructor(private config: FaConfig) {
this.setupConfiguration();
}
private setupConfiguration(): void {
if (environment.production) {
// Production settings
this.config.defaultPrefix = 'fas';
this.config.fallbackIcon = faQuestionCircle;
this.config.autoAddCss = true;
this.config.fixedWidth = false;
} else {
// Development settings
this.config.defaultPrefix = 'fas';
this.config.fallbackIcon = faExclamationTriangle;
this.config.autoAddCss = true;
this.config.fixedWidth = false;
// Additional development logging
console.log('FontAwesome configured for development');
}
}
}Understanding and configuring icon prefix behavior.
// Default prefix behavior:
// When icon is specified as string only, defaultPrefix is used
// When icon is specified as array [prefix, name], array prefix takes precedence
// When icon is specified as object {prefix, iconName}, object prefix takes precedence
type IconPrefix = 'fas' | 'far' | 'fab' | 'fal' | 'fad' | 'fat' | (string & {});Prefix Examples:
@Component({
selector: 'app-prefix-examples',
template: `
<!-- Uses defaultPrefix (e.g., 'fas') -->
<fa-icon icon="heart"></fa-icon>
<!-- Explicit prefix overrides default -->
<fa-icon [icon]="['far', 'heart']"></fa-icon>
<!-- Object format with explicit prefix -->
<fa-icon [icon]="{prefix: 'fab', iconName: 'github'}"></fa-icon>
`
})
export class PrefixExamplesComponent {
constructor(config: FaConfig) {
// Set default to regular icons
config.defaultPrefix = 'far';
}
}Graceful handling of missing icons with fallback options.
import {
faQuestionCircle,
faExclamationTriangle,
faInfoCircle
} from '@fortawesome/free-solid-svg-icons';
@Injectable()
export class FallbackIconService {
constructor(private config: FaConfig) {}
setFallbackByContext(context: 'error' | 'warning' | 'info' | 'default'): void {
switch (context) {
case 'error':
this.config.fallbackIcon = faExclamationTriangle;
break;
case 'warning':
this.config.fallbackIcon = faExclamationTriangle;
break;
case 'info':
this.config.fallbackIcon = faInfoCircle;
break;
default:
this.config.fallbackIcon = faQuestionCircle;
}
}
clearFallback(): void {
this.config.fallbackIcon = null;
}
}
// Usage in component
@Component({
template: `
<button (click)="setErrorMode()">Error Mode</button>
<button (click)="setInfoMode()">Info Mode</button>
<button (click)="clearMode()">Clear Fallback</button>
<!-- This will show fallback if 'unknown-icon' doesn't exist -->
<fa-icon icon="unknown-icon"></fa-icon>
`
})
export class FallbackDemoComponent {
constructor(private fallbackService: FallbackIconService) {}
setErrorMode(): void {
this.fallbackService.setFallbackByContext('error');
}
setInfoMode(): void {
this.fallbackService.setFallbackByContext('info');
}
clearMode(): void {
this.fallbackService.clearFallback();
}
}Controlling icon alignment and spacing globally.
// Fixed width behavior:
// When true: All icons have same width for perfect alignment
// When false/undefined: Icons use natural width
// Can be overridden per-component with fixedWidth inputFixed Width Examples:
@Component({
selector: 'app-fixed-width-demo',
template: `
<div class="icon-list">
<!-- Without fixed width - misaligned -->
<div><fa-icon icon="home"></fa-icon> Home</div>
<div><fa-icon [icon]="['fas', 'info-circle']"></fa-icon> Information</div>
<div><fa-icon icon="cog"></fa-icon> Settings</div>
</div>
<div class="icon-list-fixed">
<!-- With fixed width - aligned -->
<div><fa-icon icon="home" [fixedWidth]="true"></fa-icon> Home</div>
<div><fa-icon [icon]="['fas', 'info-circle']" [fixedWidth]="true"></fa-icon> Information</div>
<div><fa-icon icon="cog" [fixedWidth]="true"></fa-icon> Settings</div>
</div>
`,
styles: [`
.icon-list, .icon-list-fixed {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-bottom: 1rem;
}
`]
})
export class FixedWidthDemoComponent {
constructor(config: FaConfig) {
// Set global fixed width
config.fixedWidth = true;
// Now all icons will be fixed width by default
// Individual components can still override with fixedWidth input
}
}Controlling automatic CSS injection and manual CSS management.
// CSS injection behavior:
// autoAddCss: true (default) - Automatically inject required CSS
// autoAddCss: false - Manual CSS management requiredCSS Management Examples:
// Automatic CSS (recommended for most cases)
@Component({
selector: 'app-auto-css',
template: `<fa-icon icon="heart"></fa-icon>`
})
export class AutoCSSComponent {
constructor(config: FaConfig) {
config.autoAddCss = true; // Default behavior
}
}
// Manual CSS management
@Component({
selector: 'app-manual-css',
template: `<fa-icon icon="heart"></fa-icon>`,
styleUrls: ['./manual-css.component.css'] // Must include FA CSS
})
export class ManualCSSComponent {
constructor(config: FaConfig) {
config.autoAddCss = false;
// CSS must be included manually in component or globally
}
}Manual CSS Setup:
/* manual-css.component.css */
@import '~@fortawesome/fontawesome-svg-core/styles.css';
/* Or in global styles.css */
@import '~@fortawesome/fontawesome-svg-core/styles.css';Changing configuration at runtime based on user preferences or application state.
@Injectable()
export class DynamicConfigService {
constructor(private config: FaConfig) {}
applyTheme(theme: 'light' | 'dark'): void {
if (theme === 'dark') {
// Use regular icons for dark theme
this.config.defaultPrefix = 'far';
} else {
// Use solid icons for light theme
this.config.defaultPrefix = 'fas';
}
}
setAccessibilityMode(enabled: boolean): void {
// Enable fixed width for better screen reader alignment
this.config.fixedWidth = enabled;
}
setBrandMode(enabled: boolean): void {
if (enabled) {
this.config.defaultPrefix = 'fab';
} else {
this.config.defaultPrefix = 'fas';
}
}
}
// Usage in component
@Component({
template: `
<button (click)="toggleTheme()">Toggle Theme</button>
<button (click)="toggleAccessibility()">Toggle Accessibility</button>
<fa-icon icon="heart"></fa-icon> <!-- Affected by dynamic config -->
`
})
export class DynamicConfigComponent {
private isDarkTheme = false;
private isAccessibilityMode = false;
constructor(private dynamicConfig: DynamicConfigService) {}
toggleTheme(): void {
this.isDarkTheme = !this.isDarkTheme;
this.dynamicConfig.applyTheme(this.isDarkTheme ? 'dark' : 'light');
}
toggleAccessibility(): void {
this.isAccessibilityMode = !this.isAccessibilityMode;
this.dynamicConfig.setAccessibilityMode(this.isAccessibilityMode);
}
}Validating configuration settings and providing helpful errors.
@Injectable()
export class ConfigValidationService {
constructor(private config: FaConfig) {
this.validateConfiguration();
}
private validateConfiguration(): void {
// Validate default prefix
const validPrefixes = ['fas', 'far', 'fab', 'fal', 'fad', 'fat'];
if (!validPrefixes.includes(this.config.defaultPrefix)) {
console.warn(`Invalid defaultPrefix: ${this.config.defaultPrefix}`);
}
// Validate fallback icon structure
if (this.config.fallbackIcon && !this.isValidIconDefinition(this.config.fallbackIcon)) {
console.warn('Invalid fallback icon definition');
}
// Validate boolean settings
if (typeof this.config.autoAddCss !== 'boolean') {
console.warn('autoAddCss should be a boolean value');
}
}
private isValidIconDefinition(icon: IconDefinition): boolean {
return (
icon &&
typeof icon.prefix === 'string' &&
typeof icon.iconName === 'string' &&
Array.isArray(icon.icon) &&
icon.icon.length === 5
);
}
getConfigSummary(): object {
return {
defaultPrefix: this.config.defaultPrefix,
hasFallbackIcon: !!this.config.fallbackIcon,
fixedWidth: this.config.fixedWidth,
autoAddCss: this.config.autoAddCss
};
}
}Configuration recommendations for optimal Angular FontAwesome usage.
// Best practices:
// 1. Set configuration in app module initialization, not components
// 2. Use fallback icons for better user experience
// 3. Keep autoAddCss enabled unless you have specific CSS requirements
// 4. Consider fixed width for navigation menus and lists
// 5. Use consistent default prefix throughout application
// 6. Validate configuration in development modeRecommended Setup:
// app.module.ts
@NgModule({
imports: [FontAwesomeModule],
providers: [
{
provide: APP_INITIALIZER,
useFactory: (config: FaConfig, library: FaIconLibrary) => () => {
// Set consistent configuration
config.defaultPrefix = 'fas';
config.fallbackIcon = faQuestionCircle;
config.autoAddCss = true;
// Add commonly used icons
library.addIcons(faQuestionCircle, faExclamationTriangle);
if (!environment.production) {
console.log('FontAwesome configured:', {
defaultPrefix: config.defaultPrefix,
hasFallback: !!config.fallbackIcon,
autoCSS: config.autoAddCss
});
}
},
deps: [FaConfig, FaIconLibrary],
multi: true
}
]
})
export class AppModule {}