Angular Feature Toggling (4 different ways) πŸ’‘


Here are 4 different ways that you can use to add simple and powerful feature toggling to an Angular app.

toggle%20button

Today we're going to talk about Angular, feature flags and feature toggling. πŸ’‘πŸ’‘πŸ’‘

You're going to all kinds of hunky-dory stuff like...

  • How to create and use Angular feature flags.
  • The quickest way to add feature flag functionality to your Angular application.
  • A second feature flag option that is more flexible but doesn't require a special API call.
  • Using APP_INITIALIZER to call an end-point and decide if a feature should be enabled or not.
  • Bonus Point: How to help your cat purchase it's first pair of pajamas (just kidding). πŸ™€

We're going to explore 3 different ways to use feature flags in Angular and examine the pros and cons.

Ready? Let's dive in. πŸ‘‰πŸ»

  1. The simplest way to add feature toggling to your Angular app
  2. How to add feature toggling to your Angular app without needing to make a special HTTP call
  3. How to set up remote feature toggling
  4. Using the ngx-feature-toggle library

1. The simplest way to add feature toggling to your Angular app

This way is straight-forward.

It's as simple as ABC.

And easy as pie. Here's how it works.

You can use Angular's environment files to add some basic and quick feature flag capabilities to your Angular app.

Some developers might say that this is not a scalable way to create feature flags for your Angular app.

They may be right, but it's still a great way to get started without bloating your app with an initialization service. Please keep in mind that it totally depends on your scenario and use-case for feature flags. If you only have one or two feature flags that you flip on or off then this is a great option for you to consider. Does it scale? Sadly, it does not.

So we can do it like this. Open src/app/environments/environment.ts and add a flag name with the value set to true or false.

Here's a simple example.

export const environment = {
  production: false,
  feature: false
};

Next we'll generate our feature component.

ng generate component feature

Then we'll import the environment settings into our app.component.ts file and set a local variable to hold the feature's flag status. Like so.

import { Component } from '@angular/core';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'FeatureToggling';
  feature = environment.feature;
}

And finally in the app.component.html file we use ngIf to determine if the feature component is displayed or not.

<div>
  Angular Feature Flags Application
</div>
<app-feature *ngIf="feature"></app-feature>

Simple? Yeah, feature toggling in Angular doesn't have to be hard.

It boils down to a few basic steps.

  1. Add a boolean flag to your environment file.
  2. Import that boolean flag into your application wherever you want to and use it to flip things on or off.

Though this approach to feature toggling is very simple it lacks a lot of functionality because every time that you want to toggle a feature you'll be required to change the environment.ts file and re-deploy. For some environments and scenarios this does not pose any problem so it's a great approach.

But if you want a remote way to flip a switch somewhere and enable or disable a feature then let's explore a better option.

2. How to add feature toggling to your Angular app without needing to make a special HTTP call

So how can we avoid making a special HTTP call to check for feature toggles before bootstrapping the rest of the app?

We can add a feature-flags.json file to our src/app/assets/ folder with the feature toggles. This file can be changed at any time on a live server.

So how do we do it?

First we'll configure the Typescript compiler to resolve JSON modules (files). This will allow us to import JSON settings into any *.ts file.

Open tsconfig.json and set resolveJsonModule to equal true. Like so.

{
  "compileOnSave": false,
  "compilerOptions": {
    "resolveJsonModule": true,
      ...
  }
}

And then we'll create a file in the assets folder called feature-flags.json. We'll edit the file to look like this.

{
    "feature": true
}

Next, we'll edit app.component.ts to import feature flags from our new JSON file.

import { Component } from '@angular/core';
import * as FeatureFlags from '../assets/feature-flags.json';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'FeatureToggling';
  feature = FeatureFlags.feature;
}

And finally in our app.component.html file we use ngIf to hide or show the feature component based on the settings in our feature-flags.json file.

<div>
  Angular Feature Flags Application
</div>
<app-feature *ngIf="feature"></app-feature>

There! That's a bit better I'd say.

All you have to do is change the feature-flags.json file to toggle a feature on or off.

But, what if you want to be able to toggle a feature remotely?

3. How do you set up remote feature toggling? 🀷

The two approaches above might not be advanced enough for your project. So how do we use remote feature toggling? That way we can set a feature toggle remotely. For example, make the Angular application call an API before rendering the app.

We'll begin by creating a feature flag service to manage the logic of loading a feature toggle config.

ng generate service feature-flags

Next we add two functions to the service. One to load the feature flags from a remote server and the second to get a feature flag from the loaded configuration. Our service file now looks like this.

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class FeatureFlagsService {

  featureFlags: JSON;

  constructor(public httpClient: HttpClient) { }

  loadFeatureFlags(): Promise<any> {
    return this.httpClient.get("https://gist.githubusercontent.com/dkreider/dbef4a890bdc143b86d0b9330dbf2381/raw/22c03d8ed2d964a4c72fc1d35ea27dcb2adc9fd8/feature-flags.json")
      .pipe(tap((response) => this.featureFlags = response as any))
      .toPromise();
  }

  getFeatureFlag(key: string): boolean {
    return this.featureFlags[key];
  }
}

The next step is to configure our Angular application to use this service when it initializes. In our app.module.ts file we declare a new provider in the provider's section and use APP_INITIALIZER to make sure our loadFeatureFlags() function gets called at startup.

providers: [
    FeatureFlagsService,
    {
      provide: APP_INITIALIZER,
      useFactory: (featureFlagsService: FeatureFlagsService) => () => featureFlagsService.loadFeatureFlags(),
      deps: [FeatureFlagsService],
      multi: true
    }
]

In our app.component.ts file we inject the FeatureFlagsService and load a feature flag setting.

import { Component } from '@angular/core';
import { FeatureFlagsService } from './feature-flags.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'FeatureToggling';
  feature: boolean;

  constructor(public featureFlagService: FeatureFlagsService) {
    this.feature = featureFlagService.getFeatureFlag("feature");
  }

}

4. Using the ngx-feature-toggle library

Of course, there is a library built to help you do feature toggling in Angular.

It is powerful, for sure. And too complicated to dive into all its features and capabilities.

But it's a great option if none of the first 3 suit your taste or work well for your scenario.

Here's a few links for you to get started.

Which approach will you use?

And there you have it - the 3 different ways to add feature flag functionality to your Angular app.

Which approach to Angular feature flags do you plan to use?

Angular Developer

P.S. In case you’re one of the people (like me) who skim to the bottom before you read the page, here’s what this is about:

  • How to use feature flags in your Angular application.
  • A simple feature toggling option that you can set up and use in less than 3 minutes.
  • A second feature flag option that is more flexible but doesn't require a special API call.
  • Using APP_INITIALIZER to call an end-point and decide if a feature should be enabled or not.