Angular Feature Flag: a step-by-step guide with a working application

By Geshan Manandhar on November 8, 2022

Angular is the first Single Page Application (SPA) framework released initially as AngularJs in 2010. Angular is developed by Google and it is still a popular framework for developing web applications compared to its competitors. In this post, you will learn how to create an Angular feature flag to control the rendering of a feature with the click of a button. Let’s get going!

Angular Feature Flag Guide For Everyone

Prerequisites

Before you dive deeper into the code, below are some requisites to be familiar with:

  1. Some prior knowledge of JavaScript, TypeScript, and Angular will be essential. Understanding of Angular’s service, dependency injection, and directive will be necessary. For this guide, you will use Angular 14 with TypeScript.
  2. Knowing how NPM works is required, adding an NPM package with the npm command is needed
  3. A Flagsmith account is used to create a simple feature flag as part of the tutorial. Register now, it is free.

As the prerequisites have been mentioned you can be ready to get your hands dirty with the code.

Example Angular app - shop

For this guide, you will build upon the bare-bones e-shop used in the official Angular Getting started guide. It is a basic e-commerce app that lists products, you can navigate to the product detail page and add it to the cart to checkout. Among the multiple components, it has you will add a feature flag to the product list component. The e-commerce app looks like the below when you run it locally:

angular feature flag guide

The full code is available as a GitHub repository for your reference. You can also view the running app on Netlify. To get the above app running locally you can run the following commands:

1git clone [git@github.com](mailto:git@github.com):geshan/angular-feature-flag.git
2
3cd angular-feature-flag
4
5npm install
6
7npm start

First, you clone the app from GitHub then you go into the directory. After that, you install the NPM dependencies with `npm install`, then you run the app with `npm start` which will show you something like the below:

angular feature toggle guide

Subsequently, if you hit `http://localhost:4200` on your browser of choice you will see the app working.

The goal of this tutorial is to enable you to add a feature flag for the “Share” button feature. The “Share” button can be hidden or shown by disabling or enabling the feature flag on the Flagsmith interface. This does not require any code changes or any deployment/release process. In the end, you will be able to achieve this and it will look like the following:

Angular Feature Flagging

To do this you will first need to add the feature flag on Flagsmith, which is discussed in the next section.

Setup Flagsmith for feature flags

To create the Angular feature flag to show or hide the share button, you will first create a project on Flagsmith. To create a project you will click the “Create Project” button after signing up and logging in to Flagsmith:

Angular Feature Toggling

You are naming your project angular-shop to keep things simple. Then you will reach a page as follows:

Angular Feature Flags

On this page, you will click the “Create Your First Feature” button found at the end of the page. It will open a form as seen below:

create feature flag angular

You will fill in the “ID” of the feature flag, which is `show_share_button` in the above picture. Consistent naming is one of the feature flags best practices. This is a boolean feature flag that is either on or off so the value is not necessary. As the name suggests, this feature flag is used to show or hide the share button on the Angular app. Adding a description will be helpful for future reference and add tags if you think they will be useful later.

When the feature flag is created, it will look like the below:

Angular Feature Flagging Guide

You have created the feature flag named `show_share_button` and it is in an enabled state. Notice that the feature will be created in both the `Development` and the `Production` environments. For the scope of this tutorial, you will only use the Development one. In the next section, you will install the Flasmith JavaScript client, then wire it up with the Angular app.

Add Angular feature flag to the app

You have done the setup to add the feature flag to show/hide the “Share” button on the Flagsmith Web UI. Now you will need to add the SDK and the supporting code to realize the feature flag on the application. To do this, first, you will add the Flagsmith JavaScript client from NPM by executing the following command on the project root:

1npm install flagsmith --save

After the `flagsmith` client has been installed, you will first create the `feature flag service` which will load the client and check if the feature is on or off. The service is described next.

Create Angular feature flag service class

You will create the feature flag service class at `src/app/feature-flag/feature-flag.service.ts`. It will communicate with Flagsmith using its client to find out if the `show_share_button` feature flag is on or off. The code for this feature flag service looks like the below:

1import { Injectable } from '@angular/core';
2import flagsmith from 'flagsmith';
3
4flagsmith.init({
5  environmentID:"BtvpWuJ6V3YkuunRgLkFqg",
6  cacheFlags: true,
7  enableAnalytics: false,  
8});
9
10@Injectable()
11export class FeatureFlagService {
12  isFeatureOn(featureName: string) {
13    return flagsmith.hasFeature(featureName);
14  }
15}
16

First, you import `injectable` from Angular core which is used to make sure the `FeatureFlagService` class can be injected into any class that uses it as a dependency. Please read about Dependency Injection in Angular to grasp the concept better. Next, you import the `flagsmith` client from `flagsmith`. After that, you initialize the Flagsmith client with the `environmentID`. This `environmentID` can be found on the feature page in the `Initialising your project` section.

Add angular feature flag

Replace your Environment ID properly from your feature flag page. Also, keep in mind that the ID is different for the development and production environment. The Flagsmith client is initialized with caching on and analytics off.

Next, you define the class `FeatureFlagService` which is injectable and has only one method `isFeatureOn`. The main thing happening in this method, it takes in the name of the feature flag and checks if that feature flag is on or off on Flagsmith calling the client’s hasFeature method.

The next step is to add the directive that is going to use this service to show or hide the feature.

Angular feature flag directive

The service class is only responsible to communicate with Flagsmith by using its client. It checks if the feature flag is on or off but does not handle any of the rendering logic. In Angular rendering logic for the views is offloaded to a directive. Thereby, you will create an attribute directive at `src/app/feature-flag/remove-if-feature-off.ts` with the following content:

1import { Directive, ElementRef, Input, OnInit } from '@angular/core';
2import { FeatureFlagService } from './feature-flag.service';
3 
4@Directive({
5  selector: '[removeIfFeatureOff]'
6})
7export class RemoveIfFeatureOff implements OnInit {
8  @Input('removeIfFeatureOff') featureName: string;
9 
10  constructor(private el: ElementRef, private featureFlagService: FeatureFlagService) {
11    this.featureName = '';
12  }
13 
14  ngOnInit() {
15    if (!this.featureFlagService.isFeatureOn(this.featureName)) {
16      this.el.nativeElement.parentNode.removeChild(this.el.nativeElement);
17    }
18  }
19}
20

The directive starts by importing Directive, ElementRef, Input, and OInit from Angular core. It also imports the `FeatureFlagService` you created in the previous section. Then with the `@Directive` decorator, you define that the directive will be activated by the attribute `removeIfFeatureOff` on any HTML tag.

Angular decorators

Next, you export the directive class named `RemoveIfFeatureOff` that implements the `OnInit` interface. This interface has the `ngOnInit` method to initialize the directive. In the next line, you instruct that the name of the feature flag will be sent in from the attribute as `featureName` which is a string. In the constructor of the class, you set the feature name to be an empty string initially. 

Then the `ngOnInit` method is defined. In this method, if the feature flag passed via the featureName attribute is not on, then the children of that HTML attribute are removed. As it is a directive it can be added to any HTML tag and the children of that tag can be shown or removed as per the value of the feature flag. Using a directive makes it not only easy to use but very flexible as well. This will make more sense once you see the implementation of this directive in the wiring up with the product list component done in the next section.

Wire up service and directive with the product list component

To glue up the service and directive with the product list component, you will add them to the App module and component. You will add the `FeatureFlagService` to `src/app/app.component.ts` as follows:

1import { Component } from '@angular/core';
2import { FeatureFlagService } from './feature-flag/feature-flag.service';
3
4@Component({
5  selector: 'app-root',
6  templateUrl: './app.component.html',
7  styleUrls: ['./app.component.css'],
8  providers: [FeatureFlagService]
9})
10export class AppComponent { }
11

The app component is the root component of this application. If you add the service to the app component’s [providers](https://angular.io/guide/providers),  it can be used in any other component or class that wants to use it. Next, you add the  `RemoveIfFeatureOff` directive to the declarations array of the App module file `src/app/app.module.ts` as follows:

12import { RemoveIfFeatureOff } from './feature-flag/remove-if-feature-off';
3
45
6declarations: [
7  AppComponent,
8  TopBarComponent,
9  ProductListComponent,
10  ProductAlertsComponent,
11  ProductDetailsComponent,
12  CartComponent,
13  ShippingComponent,
14  RemoveIfFeatureOff
15],
16

As the directive is added to the `declarations` of the main module - the app module, it will be accessible to any sub-module or view in the application. The trigger to make it all work is to add the directive with the proper feature flag name on the product list view file at `src/app/product-list/product-list.component.html` as follows:

1<h2>Products</h2>
2
3<div *ngFor="let product of products">
4
5  <h3>
6    <a
7      [title]="product.name + ' details'"
8      [routerLink]="['/products', product.id]">
9      {{ product.name }}
10    </a>
11  </h3>
12
13  <p *ngIf="product.description">
14    Description: {{ product.description }}
15  </p>
16
17  <div [removeIfFeatureOff]="'show_share_button'">
18    <button type="button" (click)="share()">
19      Share
20    </button>
21  </div>
22
23  <app-product-alerts
24    [product]="product"
25    (notify)="onNotify()">
26  </app-product-alerts>
27
28</div>
29

In the part `<div [removeIfFeatureOff]="'show_share_button'">`, the custom attribute directive you defined earlier with attribute `removeIfFeatureOff` is used. The feature name is passed as `'show_share_button'` which is the same as the feature flag you defined in the earlier stage.

In the directive, if the feature flag is off, it will remove the child which will be the `button` tag in this case. So if the feature is on it will keep the button tag for the share button as is, else it will remove the button HTML tag which will disable the feature.

Given all the setup on the Flagsmith UI and the code is done, in the next section, you will test that the functionality with the Angular feature flag works as expected.

Test Angular feature flag toggle change

To test the feature flag, you can change the settings on the Flagsmith interface. As the feature toggle is in the “On” state the `Share` button will show up initially. When you turn off the toggle and refresh the page the `Share` button will then disappear. 

Take note that, you might need to wait a couple of seconds and it might take a couple of refreshes for the change to take effect. It is also the case because the caching of flags is turned on in the client configuration. The whole process can be seen in action below:

Angular Feature Flag example

You can see the feature flag turned off version on Netlify. All the code to add the Angular feature flag with the Flagsmith client is available as a pull request for your reference. In the next section, you will learn about further steps for Angular feature flags.

Next steps

Angular has changed a lot in the past 10 years. Currently, it is very close to how Nest.js is structured and also supports TypeScript by default. The use of services, guards, dependency injection, and directives make it easy to write SOLID code using TypeScript.

In terms of feature flags and Flagsmith, there are avenues to tap into. If you want to use the Flagsmith client directly on the browser you can do it by including the following script:

1<script src="https://cdn.jsdelivr.net/npm/flagsmith/index.js"></script>

This can be used to control feature flags even if you don’t use a framework like React.js or Vue.js. If you are using React.js you can read this blog post on JavaScript feature flags with React. You can also use feature flags in the backend with Node.js feature flags or other languages and frameworks.

In addition to that, you can use feature flags with values, not just on and off. For instance, you could control the color of the “Share” button with a feature flag that has the value of the color like blue, light blue, or dark blue. And this can be changed on the fly without the need to deploy any code changes. Learn about more of such feature flag use cases. Unlike other services, Flagsmith is open source and can also be hosted on-prem or on your private cloud.

Conclusion

In this post, you learned about Angular, the first Single Page Application (SPA) framework, and its popularity. Then you were introduced to the getting started Angular e-commerce app which you could run locally. After that, you set up a feature flag to show or hide the “Share” button on the product listing page. As the next step, you integrated the Flagsmith feature flag in the Angular app using a new service and a directive.

Feature flags help you release software with a high degree of confidence and turning a feature or off with a feature flag is a matter of clicks. There is no need to change or deploy any new code which is almost no risk.

If you want to start using Flagsmith as your Angular feature toggle software- just create your account here or contact us for the on-prem solution.

P.S. If you like this "Angular feature flag" guide, you can check out our other guides: