Feature flags angular

Feature flags angular DEFAULT

Implementing Feature Flags in Angular is easier than you thought it would be!

Feature flags are basically a configuration for your application where we specify which features are enabled/disabled. We would normally just comment out that part of the code which we don't want to be made available and then later come back and uncomment it to enable that feature.

Instead of us having to make changes in the code every time we want to enable/disable something in our application, we can make use of a configuration file where we specify if that feature is enabled/disabled.

Feature flags and why we need it

Feature flags are a very common technique that is widely used in many applications. If we are testing out a particular feature by only enabling it to a particular group of people (A/B Testing) or we need to disable a feature because it has some serious issues that would take time to fix, in these conditions it won't be practical to manually make changes in the code and push it every time we need to enable/disable something in the application. Instead what we can do is create a configuration outside the application and then use that to turn on/off features in the application with ease. This means you can make changes fast without having to make changes in the code.

Also like I mentioned in the first part If you want to enable a particular feature to only a set of people you can easily do that by sending a different set of config for these people and the default config for all the other users based on some conditions.

Implementing Feature flags in Angular

The term might make you think this is something really difficult to implement. But it's actually quite easy to do it angular with the help of some inbuilt features that Angular provides like directives, guards, etc.

Configuration File

Its ideal that this file is managed outside the application and is made available via an API call. In that way, we can easily update the config and the application gets the new file with ease.

We are going to be managing a object with the feature as the key and the value will be either or . We are going to keep it simple here, we can always create granular feature flags to get more control of the application. For the sake of this post, I would consider a module as a feature.

and the config file will be something like this:

Application Structure

Our application has 3 modules:

  • Bookmarks
  • Snippets
  • Packages

All these modules are lazy-loaded from the . So based on the configuration we have to load the modules. Also, we have a header component where links to these modules will be added. So we have to manage that as well, ie If the packages module is not enabled, we shouldn't be showing in the header.

Here is our routing module:

One thing that you can notice is that I've provided the feature name in the attribute so that we can identify which module is being loaded.

Feature Flag service

We create a feature flag service where we are going to manage all the logic for getting the config and also functions to check if a feature is enabled or not.

We are adding two function inside our service:

  • - Get the config from an API
  • - Check if a particular feature is enabled

Now that we have our service ready, we make use of . This is an provided by Angular where we can provide a function that will be called during app initialization.

Read more: angular.io/api/core/APP_INITIALIZER

Configure

We have to add our provide function so that it will call the API and loads the configuration on startup.

Create a factory that will return the call the function in our . And add in our providers array

So now when our application gets initialized, the config will be loaded in our .

Route Guard

We now can create a route guard to only load modules if the feature is enabled. For that we create a guard:

We can now update the file to include our guard:

So now when someone tries to visit the URL, the guard will check if that particular feature is enabled or not, and only then will allow navigating to that particular module. The first part is now done. The next thing we have to do is to show the header link only when the feature is enabled. For that we will be creating a Directive, to be more precise a

Feature flag directive

Directives are a really powerful feature that Angular provides. We will be creating a structural directive for our use-case:

So what we are doing here is rendering the template only if the feature is enabled. If not that particular element will not be placed in the DOM. Note that the name of the directive and the is the same so that we can receive input without having to add another attribute in the HTML.

Using the directive

This is how we use the directive in HTML:

We add the directive in and pass the key for the feature to it.

Done! We have successfully implemented Feature flags in Angular. You might feel like there is a lot of code in here, but in essence, there are 3 main things:

  1. Feature Flag Service
  2. Feature Flag Guard
  3. Feature Flag Directive

Links

These are the 3 main things that we need. Hope you are now aware of how to implement feature flags in Angular. If something is not clear, just try to read through the code line by line and it'll make sense.

🌎 Connect with me

Buy me a pizza

Do add your thoughts in the comments section. Stay Safe ❤️

Sours: https://blog.sreyaj.dev/implementing-feature-flags-in-angular

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

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

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

toggle%20button

Getting Started

How do you add feature flag functionality to your Angular application?

What's the best way to set up Angular feature toggling? And how do you use feature flags?

In this guide we'll 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

This way is straight-forward.

It's as simple as ABC.

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

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

Some experts might say that this is not a scalable way to create feature flags for your Angular app, 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? Sadly, it does not.

So we can do it like this. Open and add a flag name with the value set to true or false.

Here's a simple example.

Next we'll generate our feature component.

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

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

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 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 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 file to our 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 file.

Open and set to equal true. Like so.

And then we'll create a file in the folder called . We'll edit the file to look like this.

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

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

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

All you have to do is change the 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.

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.

The next step is to configure our Angular application to use this service when it initializes. In our 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.

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

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! 🧑🏼‍💻

Angular Consultant

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.

Unleash your skills

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

Sours: https://danielk.tech/home/add-feature-toggling-to-your-angular-app-the-ultimate-guide-2021
  1. Peter max prices
  2. Ratcheting tools
  3. Bls wage data
  4. Wayfair outdoor tablecloth
  5. 3rd gen camaro grille

npm

Dependency Statusnpm

NPMNPM

Build StatusCoverage Statusnpm bundle size (minified + gzip)npm

Your module to handle with feature toggles in Angular applications easier.

Why Feature toggle?

This is a common concept, but why use this directive instead solve it via server-side rendering?

The idea of this directive is make this process transparent and easier. So the main point is integrate this directive with other tooling process, such as:

  • Server-side rendering;
  • Progressive rendering;
  • Any other that you like :)

You can integrate with WebSockets or handling this in a EventSourcing architecture. It's totally transparent for you and you can integrate easier in your application.

Demo

Try out the demos on Stackblitz:

Install

You can get it on NPM installing module as a project dependency.

npm install ngx-feature-toggle --save

Setup

You'll need to add to your application module. So that, the components will be accessible in your application.

... import{FeatureToggleModule}from'ngx-feature-toggle'; ... @NgModule({declarations: [YourAppComponent],imports: [ ... FeatureToggleModule, ... ],providers: [],bootstrap: [YourAppComponent]})exportclassYourAppComponent{}

Now you just need to add a configuration in your application root component. Your feature toggle configuration can be added using different approaches, such as:

  • RXJS subscribe information;
  • HTTP Request;
  • CQRS event data;
  • File information;
  • etc;

After that, you can use the components and directives in your templates, passing the string based on the feature toggle configuration data.

Module

Components and Directives

  • : Handle with feature toggle configuration in your application. It adds the default values of your enabled/disabled features;
  • : Directive that handles with feature toggle check. So that, the component will be rendered/removed based on the feature toggle configuration is enabled;
  • : Directive that handles with feature toggle check. So that, the component will be rendered/removed when the feature toggle configuration is disabled;
import{Component}from"@angular/core"; @Component({selector: "component-docs",template: ` <feature-toggle-provider [features]="featureToggleData"> <div *featureToggle="'enableSecondText'"> <p>condition is true and "featureToggle" is enabled.</p> </div> <div *featureToggle="'enableFirstText'"> <p> condition is false and "featureToggle" is disabled. In that case this content should not be rendered. </p> </div> <div *featureToggle="'!enableFirstText'"> <p> condition is false and "featureToggle" is disabled <b>but it has "!" as a prefix of the feature toggle to be checked.</b> In that case this content should be rendered. </p> </div> <div class="combined-feature-toggles-with-truthly-option" *featureToggle="['!enableFirstText', 'enableSecondText']" > <p> This is a combined condition. It shows if <b>enableSecondText</b> is true and <b>enableFirstText</b> is falsy, but it has "!" as a prefix. If both cases are correct, then the "featureToggle" is enabled and rendering this component. </p> </div> </feature-toggle-provider> `,})exportclassComponentDocsComponent{publicfeatureToggleData: any={enableFirstText: false,enableSecondText: true,};}

Route Guards

In some scenarios when you need to prevent the route to be loaded, you can use , by passing the class and configuration of the feature toggle to be checked in your route data.

... exportconstroutes: Routes=[{path: 'home',component: HomeComponent,canActivate: [NgxFeatureToggleCanLoadGuard],data: {// Using array as configurationfeatureToggle: [// This configuration will check if feature toggle is enabled'enableSecondText',// This configuration will check if feature toggle is disabled// since it has `!` prefix in the configuration'!enableFirstText'],},},{path: 'dashboard',component: DashboardComponent,canActivate: [NgxFeatureToggleCanLoadGuard],data: {// Using string as configurationfeatureToggle: 'enableSecondText',},},]; ...

Also, you can use to check if the route should be activated or not by passing the class and configuration of the feature toggle to be checked in your route data.

... exportconstroutes: Routes=[{path: 'home',component: HomeComponent,canActivate: [NgxFeatureToggleRouteGuard],data: {// Using array as configurationfeatureToggle: [// This configuration will check if feature toggle is enabled'enableSecondText',// This configuration will check if feature toggle is disabled// since it has `!` prefix in the configuration'!enableFirstText'],},},{path: 'dashboard',component: DashboardComponent,canActivate: [NgxFeatureToggleRouteGuard],data: {// Using string as configurationfeatureToggle: 'enableSecondText',},},]; ...

In both route guards you can pass route data with feature toggle as an array. For scenarios when you need to check for feature toggles enabled and/or disabled you can easily configure it by passing if the application should check if the feature toggle is disabled

... exportconstroutes: Routes=[{path: 'home',component: HomeComponent,canActivate: [NgxFeatureToggleRouteGuard],data: {// Using array as configurationfeatureToggle: [// This configuration will check if feature toggle is enabled'enableSecondText',// This configuration will check if feature toggle is disabled// since it has `!` prefix in the configuration'!enableFirstText'],},},{path: 'dashboard',component: DashboardComponent,canActivate: [NgxFeatureToggleRouteGuard],data: {// Using string as configurationfeatureToggle: 'enableSecondText',},},]; ...

In this case, we are combining the checks. So the component will be activated if is configured as AND is configured as . With that configuration you can have all the flexibility to cover different scenarios in your app.

Use to control when the child component of a specific component can be activate via routing. It can be passed as an array of items.

... exportconstroutes: Routes=[{path: 'customer',component: CustomerComponent,canActivateChild: [NgxFeatureToggleRouteGuard],children: [{path: ':id',component: CustomerDetailComponent,// This is the featureToggle configuration for// the child component. It can also use// a combination of feature togglesdata: {featureToggle: [// This configuration will check if feature toggle is enabled'enableCustomerPage',// This configuration will check if feature toggle is disabled// since it has `!` prefix in the configuration'!enableChildrenNavigation'],},},],},{path: 'dashboard',component: DashboardComponent,canActivateChild: [NgxFeatureToggleRouteGuard],children: [{path: ':id',component: DashboardDetailsComponent,// This is the featureToggle configuration for// the child component. It can also use// a combination of feature togglesdata: {// using string to configurefeatureToggle: 'enableDashboardDetailsPage',},},],},]; ...

Redirects

You might have some specific requirements that you should redirect a user to a specific route in case of a feature flag is disabled. For that, you can use as a mechanism to redirect a user in a specific route when it tries to access in a route with a CanActivate/CanActivateChild/CanLoad Feature Toggle Guard and the feature toggle is disabled.

For advanced scenarios you can use a combination of route guards AND redirects. E.G.

... exportconstroutes: Routes=[{path: 'customer',component: CustomerComponent,canLoad: [NgxFeatureToggleRouteGuard],canActivate: [NgxFeatureToggleRouteGuard],canActivateChild: [NgxFeatureToggleRouteGuard],// This is the featureToggle configuration for// the parent componentdata: {featureToggle: ['enableCustomerPage'],// If feature toggle is disabled, the user will be redirected to `/error` URLredirectTo: '/error'},children: [{path: ':id',component: CustomerDetailComponent,// This is the featureToggle configuration for// the child component. It can also use// a combination of feature togglesdata: {featureToggle: ['enableCustomerPage','!enableChildrenNavigation'],// If one (or all of them) of the feature toggle is disabled, the user will be redirected to `/customer-error` URL// Note that you can use redirects for the main url and their childrenredirectTo: '/customer-error'},},],},]; ...

Development

Run demo locally

  1. This project uses Angular CLI as base. That means you just need to run and access the link in your browser

Run tests

  1. Run for run tests. In case you want to test using watch, please use

Publish

this project is using package to publish, which makes things straightforward. EX:

For more details, please check np package on npmjs.com

Contribute

For any type of contribution, please follow the instructions in CONTRIBUTING.md and read CODE_OF_CONDUCT.md files.

Author

Wilson Mendes (willmendesneto)

Sours: https://www.npmjs.com/package/ngx-feature-toggle
What are Feature Flags?

Implementing Feature Flags in an Angular

Feature flagging is a well-known technique that improves development speed and allows teams to test new features before they’re stable. It can be used for several reasons: A/B testing for specific features, deploying a feature to a small target audience to get feedback on it, or continuous code delivery.

In this article, we’ll learn how we can leverage various Angular features in order to prevent entering or viewing prohibited areas. Let’s get started.

In our application, we use a commercial service for feature flag management, which exposes a GUI, where we can add or update our application feature flags. I won’t mention the service name, as advertising it isn’t the point of this article.

Our backend is responsible for the communication with the provider, and provides us with the user’s features flag values upon login. A typical response would look like this:

user.js

We need to preemptively fetch the user’s data from the server, and make it available to our components before we allow the user to interact with them. Luckily, Angular makes doing that it a breeze, by exposing the  injection token.

The  provider can take a function that returns a promise, and only when that promise is resolved, Angular will bootstrap the application.

For the purpose of our demo we’ll use Akita, although you can employ any state management solution for this purpose. Let’s quickly scaffold a :

user.query.ts

user.store.ts

The  query method returns the current state. In our case, we need the user  in order to check if we can render the view.

Now, let’s create the :

ff-service.ts

We expose a  method which is responsible for initializing the store with the user’s data via a server request ( in this case it’s simulated).

Now, let’s use our  with the  token to load the user’s data before the app loads:

app.module.ts 

We provide the  with the  function, which calls the service’s  method. This will ensure that the user’s data will be in our store before the application loads.

Now, that we have the user’s data, we can move forward and create our structural directive.

Structural directives are responsible for HTML layout. They shape or reshape the DOM’s structure, typically by adding, removing, or manipulating elements, and that’s exactly what we need.

The  structural directive will be in charge of displaying a provided template, in a DRY way, based on whether the user is authorized that template. Let’s create it:

featureFlag.directive.ts

A structural directive creates an embedded view from the Angular-generated  and inserts that view in a view container adjacent to the directive’s original host element.

We pass the provided  from the input to the  query method, and based on the value it returns, we can determine whether or not we should render the template. Let’s use the directive:

c.html

Notice that the directive can support an array of flags. We can even take it one step further and add support for an  condition. Here’s some quick pseudo-code for this functionality:

withOr.html

withOr.ts

The can be done through the template directives. You can read more about this syntax in this great blog post.

Let’s move forward and implement the routing guards, which will prevent navigation from unauthorized users.

Applications often restrict access to certain areas based on the user’s identity. For that purpose, we can implement a guard which only permits access to authorized users, based on their feature flags.

ffguard.ts 

routes.ts

In the above example we’re checking whether the user has the appropriate feature flag permissions detailed in the route data, in which case we permit the navigation; Otherwise, we redirect the user to the home page.

Many applications leverage Angular’s lazy load feature in conjunction with the  option, in order to preload (i.e., download in advance) lazy modules, so that they’ll be available when the user navigates to them.

In our case, we don’t want to preload modules that the user isn’t authorized to view. In such cases, we can implement our own  that provides a way to intercept and determine whether any lazy module should be preloaded.

Let’s see how can we do this:

pl2.ts

pl3.ts

Similarly to the previous example, in this example, the flags in the route data again dictate whether the user can reach the route. If that’s the case, we return the provided  function; Otherwise, we return an observable, indicating to the router that the user should be redirected instead.

We’re not done yet. The previous case doesn’t cover situations where the user directly navigates to the protected URL. For these cases, we need to use the  guard:

FeatureFlagCanLoad.ts

routesv3.ts

Now we’ve made sure that Angular will not allow the lazy loading of a module if the user doesn’t have the required feature flags. In contrast, if we only use the  guard, it would download the module, but prevent navigation.

If from some reason you couldn’t use the  functionality, you can switch to using an observable, listen to the store value, and update the view on its initial setting.

One of the leading state management libraries, Akita has been used in countless production environments. It is constantly being developed and improved.

Whether it is entities arriving from the server or UI state data, Akita has custom-built stores, powerful tools, and tailor-made plugins, which all help to manage the data and negate the need for massive amounts of boilerplate code. We/I highly recommend that you try it out.

Further reading:

☞ Listen Changes In Reactive Form Controls Using valueChanges In Angular

☞ 7 Ways to Make Your Angular App More Accessible

☞ Angular RxJS: Observables, Observers and Operators Introduction

☞ Real Time Apps with TypeScript: Integrating Web Sockets, Node & Angular

☞ Angular 8 - Reactive Forms Validation Example

☞ Angular vs React vs Vue: Which is the Best Choice for 2019?

☞ A comparison between Angular and React

#angular #angular-js

What is GEEK

Buddha Community

Implementing Feature Flags in an Angular
Sours: https://morioh.com/p/a678b654c472

Flags angular feature

Angular How-to: Implement Feature Flags

Developer

Senior Dev Consultant Laurie Atkinson demonstrates how to turn features on and off via configuration or from a database. This may include hiding and disabling UI elements, changing code flow, or preventing routing to components.


In an agile development environment, there may be partially completed features or features with external dependencies that are not ready. Instead of relying on multiple code branches, instead you may opt for deploying code with a feature turned off. Later, that feature should be turned on via a configuration or database change. This post provides sample code that you can use to implement feature flags in your Angular app.

Option 1: Define features in a config file

One option for storing feature flags is in a JSON configuration file. Refer to this post for an explanation on consuming an editable configuration file.

config.dev.json

{ . . . "features": { "feature1": true, "feature2": false } }

app-config.model.ts

export interface IAppConfig { . . . features: { [name: string]: boolean; }; }

Create a feature flag service

Centralize the management of determining whether a feature is turned on or off into an Angular service.

feature-flag.service.ts

import { Injectable } from '@angular/core'; import { AppConfig } from '../../app.config'; @Injectable() export class FeatureFlagService { featureOff(featureName: string) { // Read the value from the config service if (AppConfig.settings.features.hasOwnProperty(featureName)) { return !AppConfig.settings.features[featureName]; } return true; // if feature not found, default to turned off } featureOn(featureName: string) { return !this.featureOff(featureName); } }

Option 2: Use an API instead of a config file to get feature flags

Instead of reading feature flags from a config file, another option is to retrieve the features from the server via an API that could read these values from a database. The feature-flag service could be adapted to fetch the feature flag values as soon as the app starts.

feature-flag.service.ts

export class FeatureFlagService { private _featureFlags: Array<string> = []; // A list of all features turned ON private _initialized = false; constructor(private featureFlagDataService: FeatureFlagDataService) { } featureOff(featureName: string) { return !this.featureOn(featureName); } featureOn(featureName: string) { if (!featureName) { return true; } // Find the feature flag that is turned on return this._featureFlags && !!this._featureFlags.find(feature => { return feature === featureName; }); // if feature not found, default to turned off } get initialized() { return this._initialized; } // This method is called once and a list of features is stored in memory initialize() { this._featureFlags = []; return new Promise((resolve, reject) => { // Call API to retrieve the list of features and their state // In this case, the method returns a Promise, // but it could have been implemented as an Observable this.featureFlagDataService.getFeatureFlags() .then(featureFlags => { this._featureFlags = featureFlags; this._initialized = true; resolve(); }) .catch((e) => { resolve(); }); }); }

Create attribute directives to hide and disable elements

To hide an element based on whether a feature is turned on or off, use the following code to create a directive. This will enable the Angular templates to use this syntax:

<div [myRemoveIfFeatureOff]="'feature1'"> <div [myRemoveIfFeatureOn]="'feature2'">

remove-if-feature-off.directive.ts

import { Directive, ElementRef, Input, OnInit } from '@angular/core'; import { FeatureFlagService } from '../../services/feature-flag.service'; @Directive({ selector: '[myRemoveIfFeatureOff]' }) export class MyRemoveIfFeatureOffDirective implements OnInit { @Input('myRemoveIfFeatureOff') featureName: string; constructor(private el: ElementRef, private featureFlagService: FeatureFlagService) { } ngOnInit() { if (this.featureFlagService.featureOff(this.featureName)) { this.el.nativeElement.parentNode.removeChild(this.el.nativeElement); } } }

remove-if-feature-on.directive.ts

. . . @Directive({ selector: '[myRemoveIfFeatureOn]' }) export class MyRemoveIfFeatureOnDirective implements OnInit { @Input('myRemoveIfFeatureOn') featureName: string; // Same as myRemoveIfFeatureOff except call featureOn() }

Call the feature flag service elsewhere in the app

In addition to the attribute directives, the feature flag service can be called throughout the app. For instance, a menu service could use the featureOn method to hide menu items if the user does not have the required permission.

menu.service.ts

private showMenuItem(featureName: string) { return this.featureFlagService.featureOn(featureName); }

Prevent routing to component

If access to a component should be prevented when a feature is turned off, this can be accomplished by using the canActivate option available in Angular’s router.

my-routing.module.ts

{ path: 'my-component', component: MyComponent, canActivate: [FeatureFlagGuardService], data: { featureFlag: 'feature1' } },

feature-flag-guard.service.ts

@Injectable() export class FeatureFlagGuardService implements CanActivate { constructor(private featureFlagService: FeatureFlagService) { } canActivate(route: ActivatedRouteSnapshot): Promise<boolean> | boolean { // Get the name of the feature flag from the route data provided const featureFlag = route.data['featureFlag']; if (this.featureFlagService.initialized) { if (featureFlag) { return this.featureFlagService.featureOn(featureFlag); } return true; // no feature flag supplied for this route } else { const promise = new Promise<boolean>((resolve, reject) => { this.featureFlagService.initialize() .then(() => { if (featureFlag) { resolve(this.featureFlagService.featureOn(featureFlag)); } else { resolve(true); } }).catch(() => { resolve(false); }); }); return promise; } } }

This implementation of feature flags has proven to be helpful on my current project and has allowed us to proceed with the development of new features without the risk of introducing new functionality before QA is ready. I’ve introduced a few enhancements along the way, including:

  • addition of a scope for the feature – meaning the feature is available only for certain criteria
  • an option for the route guard to check for any of an array of features’ being turned on
if (this.featureFlagService.anyFeatureOn(['feature1', 'feature2', 'feature3'])) { canActivate: [FeatureFlagGuardService], data: { anyFeatureFlags: ['feature1', 'feature2', 'feature3'] } }

Also, it is worth highlighting that if a feature name is misspelled either in the configuration or in the code, then it is considered turned off. The effect of this approach is that a feature will not accidentally be turned on.

Developer Support

App Dev Customer Success Account Manager, Microsoft Developer Support

Follow

Sours: https://devblogs.microsoft.com/premier-developer/angular-how-to-implement-feature-flags/
[Frontend]: How to code Feature flags in Angular

Implementing and testing an Angular feature flag directive

Introduction

An important goal of agile software development is to shorten the user feedback loop. To achieve that you want to release your changes as often as possible. This also includes releasing prototypes, e.g. to a smaller audience, gathering customer feedback that can be used to adjust the requirements and priorities accordingly.

Methodologies such as continuous integration and continuous deployment (CI/CD) aim to automate as much of the integration and release process as possible. This way, releasing new software can happen by simply merging a code change into the main branch. Ideally, no manual interaction is needed after to reviewing, approving, and merging a merge request.

When it comes to development workflows, trunk-based development is becoming increasingly popular. Short-lived feature branches help your developers to iterate quickly on new ideas and functionality and reduce the risk of “big-bang” deployments containing massive changes.

In order to be able to merge code and deploy that is not yet ready to be shown to all your customers, you will most likely have to use feature flags. A feature flag is typically a binary value, indicating whether a certain feature is visible in a specific environment. In a very simple setup this can mean that a button or input field is only visible during local development but invisible in production.

In this blog post we want to take a look at how to implement a feature flag directive in Angular such that you can toggle the rendering of certain components as needed. The remainder of the post is structured as follows. First we will discuss different types of feature flags. After that we are going to take a look at an implementation of a structural feature flag directive in Angular together with the respective test. We are closing the post by summarizing our main findings.

Feature flag types

Feature flags can be designed in different ways, ranging from a simple on-off switch, over flags based on environments, all the way to a fully flexible and dynamic setup where your product owner can enable and disable features on-the-fly and also for certain users only.
Which implementation is best for you depends on your use case.

If you have a multi-stage deployment (e.g. development, staging, and production) and you just want to work with short-living branches then having feature flags based on environment variables are probably enough. If your goal is to perform user experiments such as A/B testing, then you might need a more sophisticated solution that involves an external service.

The available types and tools also depend on whether you need to toggle features in the front end, back end, or both. I personally was mainly working on back end code and used feature flags based on environment variables that are passed to the application at runtime. You can then use a configuration library to extract the toggle values and check in a simple  statement whether to execute some piece of code or not.

In frameworks that work with the concept of reusable UI components, it is a common use case to hide certain components from the user based on feature flags. In Angular, this can be accomplished by adding a custom directive. Let’s take a look at how we can implement and test such a feature flag directive.

Angular feature flag directive

Implementation

The goal of the feature flag directive is very similar to the  directive: Based on the input decide whether to render a component or not. The difference to a simple  is that the feature flag directive has a dependency on the service that knows which features are enabled.

Consequently, the input into the feature flag directive is simply a string indicating the name of the feature we want to condition on. Additionally, we do not have to include the feature flag service dependency in the parent component.

There are multiple tutorials on how to implement a feature flag directive in Angular already (e.g. “Feature Toggling with Angular and the Angular CLI” or “Implementing Feature Flags in an Angular”). The following listing contains my version of the feature flag directive written in TypeScript.

The job of the directive is to conditionally render the component it is attached to. This can only be achieved by using it as a structural directive (). Angular will then wrap the component in a template and inject the respective  into the constructor of the directive.

By also injecting the  we can check the feature flag service (e.g. ) if the given feature is enabled. Based on the result we create the embedded view in the view container, passing the template reference as an argument.

How you implement the feature flag service is up to you. In our example we are using a mechanism based on environment variables as described in “How to use environment variables to configure your Angular application without a rebuild”. Even though I found multiple posts on how to write a feature flag directive, none of them featured how to write tests. So let’s look into that next.

Testing

When testing the feature flag directive there are two test cases we are interested in: Testing that a component with the feature flag directive is

  1. rendered if the feature is enabled
  2. not rendered if the feature is disabled.

I am using the shallow-render package to render the component and jasmine as the testing framework. Shallow render has three advantages over the use of  for this test. Firstly, we don’t need to create a dummy component class but can instead use a simple . Secondly, we can use the  instead of having to configure a testing module. Thirdly, it has built-in support for providing mocks.

The following listing contains the unit test for the feature flag directive.

The structure of each test is very simple. The first instruction renders the  with either the feature flag enabled or disabled. We are relying on a mocked  that returns the respective value when queried for the feature status. The second instruction checks whether the  has actually been rendered or not.

Summary

In this post we have seen that feature flags are an important ingredient of agile software development. They enable you to work with short-lived branches, merging to master frequently. Additionally they can be used to dynamically test different feature combinations for different audiences.

In Angular you can use structural directives to annotate components that are supposed to be rendered conditionally based on your feature flags. This works well independently of the way you implement your feature flag service, whether it be based on environment variables or a web service. We also looked at how to test the feature flag directive using shallow-render and jasmine.

Have you used feature flags before? Did you use or write your own feature flag directive in Angular? If you have a more powerful implementation, please feel free to share some details as well as the use case for it.

Sours: https://blog.codecentric.de/en/2020/05/implementing-and-testing-an-angular-feature-flag-directive/

You will also like:

# How to Add Azure Feature Flags to Angular projects

# Feature Flags are your friends

When you are working on a big feature, you need to make sure that your code still works with all the other code and doesn't break anything. The easiest way to do that, is to get the code of your big feature in the main code branch to see if it works. The problem with this approach is that you end up with unfinished features in your main code. Feature flags allow you to hide features until they are done and switch them on or off dynamically, without changing code. This is great for unfinished features and also for experimenting with features. You can switch them on to see if and how they are used and off again when you need to.

A feature flag is a boolean value that you set in an external system. The value is read by your application and determines if a feature is shown or activated. In Azure, you can use the Feature Manager(opens new window) of the Azure App Configuration Service(opens new window) to manage feature flags. In this post, we'll see how to use these in an Angular application.

# Prerequisites

If you want to follow along, you'll need the following:

# Using Feature Flags in an Angular application

We'll create an Azure App Configuration service and add a feature flag to it, so that we can use that in an Angular application. Let's start by creating the App Configuration in the Azure portal:

  1. Go to the Azure portal(opens new window)
  2. Click the Create a resource button (the plus-sign in the top left corner)

(Create an App Configuration in the Azure portal)

  1. Search for App Configuration and select the result. This opens the Create App Configuration blade
    1. Select a Resource Group
    2. Fill in a Name
    3. Select a Location
    4. Select a Pricing Tier. The free tier is fine for this example
    5. Select Review + create and Create after that. This creates the App Configuration Service

Once the App Configuration is created, we need to create a feature flag in it.

  1. Go to the App Configuration service in the Azure portal
  2. Select the Feature manager menu
  3. Select Add to add a new feature flag
  4. Type in a Key name. Let's use "ShowCounter"
  5. Leave the rest as it is and select Apply to add the feature flag. That's it

(Add Feature Flag in the Azure portal)

  1. Also, still in the App Configuration in the Azure portal, navigate to the Access Keys menu
  2. Select Read-only keys
  3. Copy the connection string. We'll need this later

We now have a configured App Configuration with a feature flag in it. Let's create the Angular app and read the flag from there.

  1. Open Visual Studio
  2. Select Create a new project
  3. Select ASP.NET Core Web Application and select Next
  4. Pick a name and location for the application and select Create
  5. In the dialog that pos up, select Angular and select Create. This creates an ASP.NET Core application with an Angular front-end

(ASP.NET Core application with Angular front-end in Visual Studio)

Let's change the Angular part of the application so that it connects to the App Configuration and retrieves the feature flag. As this is an ASP.NET Core application, we could connect to App Configuration on the server, but I want to show you how to do all of this client-side. The goal is to show and hide the counter menu item with a feature flag.

  1. To connect to the App Configuration from Angular, we need to add two packages to the Angular app. We can do this by adding them in the package.json file, which you can find in the ClientApp folder, with the rest of the Angular application. Open package.json
  2. Insert the following lines of code into the dependencies section:

1
2

  1. Open ClientApp/src/app/nav-menu/nav-menu.components.ts. This is the class responsible for the navigation menu. Change the class to look like the code below. This code imports the App Configuration Client from the package and creates a new parameter called counterFeature. It gets the value for the counterFeature from the ShowCounter method that connects to App Configuration and retrieves the feature flag. You need to insert the read-only connection string to App Config in the conn const. It should be the read-only connection string, because this string will be published to the client and therefore you should assume that anybody can access it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

  1. Open ClientApp/src/app/nav-menu/nav-menu.components.html. This contains the HTML for the navigation menu. Find the list item for the counter and replace its code with the code below. This reads the counterFeature parameter and toggles the visibility attribute based on that. I use the async keyword for it, because we retrieve the counterFeature using the async method ShowCounter.

1
2
3

That's it! Now run the application and see what happens. When the application opens, you should see something like the image below, with the counter menu item missing. That is because, by default, the feature flag that we've added is disabled.

(Counter menu invisible)

Now go back to the Azure portal and to the feature flag and toggle its state to On by clicking on On. Now go back to the application and refresh the screen.

(Counter menu visible after feature flag was toggled)

The counter menu is now visible, without changing code or redeploying the application.

# Conclusion

Azure App Configuration Service(opens new window) enables you to create feature flags that can dynamically show or hide features in your application, without changing code or redeploying your app. Go and check it out!

Edit this page on GitHub(opens new window)

Last Updated:10/21/2020, 2:00:00 AM

← Tip 287 - How to use a GraphQL on Azure
Tip 290 - How to secure a Blazor application with Azure Active Directory →

Sours: https://microsoft.github.io/AzureTipsAndTricks/blog/tip289.html


1243 1244 1245 1246 1247