Blog>
Snippets

Optimizing Angular Application Performance with TanStack Config

Provide an example of using TanStack Config in an Angular project to manage feature toggles, illustrating how to enable or disable features dynamically for performance optimization.
import { Injectable } from '@angular/core';
import { ConfigService } from '@tanstack/angular-config';

@Injectable({
  providedIn: 'root'
})
export class FeatureToggleService {
  constructor(private configService: ConfigService) {}

  isFeatureEnabled(featureName: string): boolean {
    // Retrieve the feature toggles from TanStack Config
    const featureToggles = this.configService.get('featureToggles') || {};
    // Check if the specific feature is enabled
    return !!featureToggles[featureName];
  }
}
This Angular service uses TanStack Config to manage feature toggles. It injects the ConfigService provided by @tanstack/angular-config to access application configuration. The isFeatureEnabled method accepts a feature name and checks the 'featureToggles' config for its status, returning true if the feature is enabled.
import { Component, OnInit } from '@angular/core';
import { FeatureToggleService } from './feature-toggle.service';

@Component({
  selector: 'app-feature-component',
  template: `<div *ngIf="isFeatureEnabled">This is a feature toggled component.</div>`
})
export class FeatureComponent implements OnInit {
  isFeatureEnabled = false;

  constructor(private featureToggleService: FeatureToggleService) {}

  ngOnInit(): void {
    // Check if the feature is enabled on component initialization
    this.isFeatureEnabled = this.featureToggleService.isFeatureEnabled('newUIFeature');
  }
}
This Angular component demonstrates how to use the FeatureToggleService to conditionally render UI elements based on the feature toggle status. It checks if the 'newUIFeature' is enabled using the service and uses *ngIf in the template to conditionally display content.