DEV Community

Daniel Kreider
Daniel Kreider

Posted on • Originally published at danielk.tech

Add Feature Toggling to your Angular app (The Ultimate Guide 2020)

The ultimate guide to implementing feature flag functionality in your Angular application

Let's explore 3 different ways that you can use to add simple and powerful feature toggling to an Angular app.

Getting Started

How do you add feature flag functionality to your Angular application? In this guide we'll explore 3 different ways and examine the pros and cons.

Ready? Let's dive in. 👉🏻

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

This way is straightforward.

It's as simple as ABC.

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

You can make use of the environment files to add feature flag capability to your Angular app.

Some experts might say that this is not a scalable way to tack on feature flags, and while they may be right, 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. 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? Nope. Not at all.

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
};
Enter fullscreen mode Exit fullscreen mode

Next we'll generate our feature component.

ng g c feature

Next 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;
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 way is stupidly-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,
      ...
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

3. But how do you setup remote feature toggling? 🤷

The two approaches above might not be advanced enough for your project. So how do we setup remote feature toggling where 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 g s 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];
  }
}
Enter fullscreen mode Exit fullscreen mode

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
    }
]
Enter fullscreen mode Exit fullscreen mode

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");
  }

}
Enter fullscreen mode Exit fullscreen mode

Conclusion

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

Questions or comments? Don't hesitate to contact me! 🧑🏼‍💻

Alt Text

Further Reading

https://martinfowler.com/articles/feature-toggles.html

https://blog.theodo.com/2016/08/feature-toggling-in-angular-with-20-lines-of-code/

https://christianlydemann.com/how-to-use-feature-toggle-in-angular-apps/

https://netbasal.com/the-ultimate-guide-to-implementing-feature-flags-in-angular-applications-d4ae1fd33684

Top comments (0)