Elvis Miranda

Elvis Miranda

1566868050

Implementing Feature Flags in an Angular

A Brief Overview

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.

Using a Feature Flag Provider

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:

{
	  "name": "Netanel",
	  "featureFlags": {
	    "data-canvas-radar-widget": true
	    "data-canvas-scatter-plot-widget": true
	  }
	}

user.js

Preload the User’s Feature Flags

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 APP_INITIALIZER injection token.

The APP_INITIALIZER 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 UserStore:

@Injectable({ providedIn: 'root' })
	export class UserQuery extends Query<UserState> {
	

	  constructor(protected store: UserStore) {
	    super(store);
	  }
	

	  hasFlags(flags: string | string[]): boolean {
	    const userFlags = this.getValue().featureFlags;
	    return coerceArray(flags).every(current => userFlags[current]);
	  }
	}

user.query.ts

@Injectable({ providedIn: 'root' })
	@StoreConfig({ name: 'user' })
	export class UserStore extends Store<UserState> {
	

	  constructor() {
	    super(createInitialState());
	  }
	

	}

user.store.ts

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

Now, let’s create the UserService:

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

	  constructor(private userStore: UserStore) {}
	

	  getUser() {
	    const fakeUser = {
	      name: 'Netanel',
	      featureFlag: {
	        a: true,
	        b: false
	      }
	    };
	

	    return timer(300).pipe(
	      mapTo(fakeUser),
	      tap(user => this.userStore.update(user))
	    );
	  }
	

	}

ff-service.ts

We expose a getUser 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 UserService with the APP_INITIALIZER token to load the user’s data before the app loads:

export function preloadUser(userService: UserService) {
	  return function() {
	    return userService.getUser().toPromise();
	  };
	}
	

	@NgModule({
	  ...
	  providers: [
	    {
	      provide: APP_INITIALIZER,
	      multi: true,
	      useFactory: preloadUser,
	      deps: [UserService]
	    }
	  ]
	})
	export class AppModule {}

app.module.ts 

We provide the APP_INITIALIZER with the preloadUser function, which calls the service’s getUser 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.

Creating the *featureFlag 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 featureFlag 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:

@Directive({
	  selector: '[featureFlag]'
	})
	export class FeatureFlagDirective {
	  @Input() featureFlag: string | string[];
	

	  constructor(
	    private vcr: ViewContainerRef,
	    private tpl: TemplateRef<any>,
	    private userQuery: UserQuery
	  ) {
	  }
	

	  ngOnInit() {
	    if (this.userQuery.hasFlags(this.featureFlag)) {
	      this.vcr.createEmbeddedView(this.tpl);
	    }
	  }
	

	}

featureFlag.directive.ts

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

We pass the provided flags from the input to the hasFlags() 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:

<div *featureFlag="'a'">...</div>
	

	<div *featureFlag="['a', 'd']">...</div>

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 or condition. Here’s some quick pseudo-code for this functionality:

<div *featureFlag="'a' or 'c'">...</div>

withOr.html

export class FeatureFlagDirective {
	  @Input() featureFlag: string | string[];
	  @Input() featureFlagOr: string = '';
	  
	  ...
	

	  ngOnInit() {
	    if (this.userQuery.hasFlags(this.featureFlag) || 
	        this.userQuery.hasFlags(this.featureFlagOr)
	     ) {
	      this.vcr.createEmbeddedView(this.tpl);
	    }
	  }
	

	}

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.

Implementing the Can Activate Guard

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.

@Injectable({ providedIn: 'root' })
	export class FeatureFlagGuard implements CanActivate {
	  constructor(private userQuery: UserQuery) {
	  }
	

	  canActivate(route: ActivatedRouteSnapshot): boolean {
	    return this.userQuery.hasFlags(route.data.flags);
	  }
	}

ffguard.ts 

const routes: Routes = [
	  ...
	  {
	    path: '...',
	    component: ProtectedComponent,
	    canActivate: [FeatureFlagGuard],
	    data: {
	      flags: 'b' // or ['a', 'b']
	    }
	  }
	];

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.

Implementing a Custom Preload Strategy

Many applications leverage Angular’s lazy load feature in conjunction with the preload 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 [preloadStrategy](https://angular.io/api/router/PreloadingStrategy "preloadStrategy") that provides a way to intercept and determine whether any lazy module should be preloaded.

Let’s see how can we do this:

@Injectable({ providedIn: 'root' })
	export class AppPreloadingStrategy implements PreloadingStrategy {
	  constructor(private userQuery: UserQuery) {
	  }
	

	  preload(route: Route, load: () => Observable<any>): Observable<any> {
	    return this.userQuery.hasFlags(route.data.flags) ? load() : of(false);
	  }
	}

pl2.ts

const routes: Routes = [
	  {
	    path: 'bar',
	    loadChildren: () => import('./bar/bar.module').then(m => m.BarModule),
	    data: {
	      flags: 'a'
	    },
	  }
	];
	

	@NgModule({
	  imports: [RouterModule.forRoot(routes, { preloadingStrategy: AppPreloadingStrategy })],
	  exports: [RouterModule]
	})
	export class AppRoutingModule {
	}

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 load() function; Otherwise, we return an observable, indicating to the router that the user should be redirected instead.

Implementing the Can Load Guard

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 canLoad guard:

@Injectable({ providedIn: 'root' })
	export class FeatureFlagCanLoad implements CanLoad {
	  constructor(private userQuery: UserQuery) {
	  }
	

	  canLoad(route: Route): boolean {
	    return this.userQuery.hasFlags(route.data.flags);
	  }
	}

FeatureFlagCanLoad.ts

const routes = [{
	  path: 'bar',
	  loadChildren: () => import('./bar/bar.module').then(m => m.BarModule),
	  data: {
	    flags: 'b'
	  },
	  canLoad: [FeatureFlagCanLoad]
	}]

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 canActivate guard, it would download the module, but prevent navigation.

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

🚀 Have You Tried Akita Yet?

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
Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Jack Salvator

Jack Salvator

1608113009

New Angular 7 Features With Example - Info Stans

What is new in New Angular 7? New Angular 7 features have turned out as a powerful release that really brought advancement in the application development structure.

Here, we have listed new Angular 7 features with examples and write the difference between Angular 6 and Angular 7.

  • Bundle Budget
  • Virtual Scrolling
  • Error Handling
  • Documentation Updates
  • Application Performance
  • Native Script
  • CLI Prompts
  • Component in angular 7
  • Drag and Drop
  • Angular Do-Bootstrap

Read more: Angular 7 Features With Example

#angular 7 features #what’s new angular 7 #new angular 7 features #angular 7 features with examples

Loma  Baumbach

Loma Baumbach

1600476300

Getting Started With Feature Flags

Introduction

As any developer can tell you, deploying any code carries technical risk. Software might crash or bugs might emerge. Deploying features carries additional user-related risk. Users might hate the new features or run into account management issues. With traditional deployments, all of this risk is absorbed at once.

Feature flags give developers the ability to separate these risks, dealing with one at a time. They can put the new code into production, see how that goes, and then turn on the features later once it’s clear the code is working as expected.


What is a Feature Flag?

Simply put, a feature flag is a way to change a piece of software’s functionality without changing and re-deploying its code. Feature flags involve creating a powerful “if statement” surrounding some chunk of functionality in software (pockets of source code).


The History of Feature Flags

Leading Web 2.0 companies with platforms and services that must maintain performance among high traffic levels led the way in regard to developing and popularizing new deployment techniques. Facebook, in particular, is known as a pioneer of feature flags and for releasing massive amounts of code at scale. While building its massive social network more than a decade ago, the company realized that its uptime and scale requirements could not be met with traditional site maintenance approaches. (A message saying the site was down while they deployed version 3.0 was not going to cut it).

Instead, Facebook just quietly rolled out a never-ending stream of updates without fanfare. Day to day, the site changed in subtle ways, adding and refining functionality. At the time, this was a mean feat of engineering. Other tech titans such as Uber and Netflix developed similar deployment capabilities as well.

The feature flag was philosophically fundamental to this development and set the standard for modern deployment maturity used by leading organizations everywhere today. Recently, feature flags have been used in tandem with continuous delivery (CD) tools to help forward-looking organizations bring features, rather than releases, to market more quickly.

#devops #continuous integration #ci/cd #continous delivery #feature flags #flags #feature branching #feature delivery

Roberta  Ward

Roberta Ward

1593184320

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.

Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.

We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.

What is a Component in Angular?

Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']
})

Role of App Module

Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.

@NgModule({
declarations: [
  AppComponent,
],
imports: [
  BrowserModule,
  HttpClientModule,
  AppRoutingModule,
  FormsModule
],
bootstrap: [AppComponent]
})

What is Data Binding?

Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:

  • When there is a requirement to output data from our Typescript code in the HTML template. String interpolation handles this purpose like {{data}} in HTML file. Property Binding is also used for this purpose like [property] = “data”.
  • When we want to trigger any event like clicking a button. Event Binding works while we react to user events like (event) = “expression”.
  • When we can react to user events and output something at the same time. Two-way Binding is used like [(ngModel)] = “data”.

image for understanding data binding

#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular

Ayyaz Zafar

1624138795

Angular Material Autocomplete - Multiple Use Cases covered

Learn How to use Angular Material Autocomplete Suggestions Search Input. I covered multiple use cases.

Please watch this video. I hope this video would be helpful for you to understand it and use it in your projects

Please subscribe: https://www.youtube.com/channel/UCL5nKCmpReJZZMe9_bYR89w

#angular #angular-material #angular-js #autocomplete #angular-material-autocomplete #angular-tutorial