All files / lib/directives/feature-flag feature-flag.directive.ts

100% Statements 12/12
100% Branches 8/8
100% Functions 3/3
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 32 33 34 35 36 37 38 39 40 41 42 43 44 45                              1x 9x   9x   9x         8x 8x 1x 1x     7x 7x       7x 3x              
import { Directive, inject, Input, OnChanges, SimpleChange, SimpleChanges, TemplateRef, ViewContainerRef } from '@angular/core';
import { Store } from '@ngrx/store';
import { tap } from 'rxjs/operators';
 
import { IFeatureAccessState } from '../../feature-access.interface';
import { featureAccessSelector } from '../../feature-access.selectors';
 
interface IInputChanges extends SimpleChanges {
  appFeatureFlag: SimpleChange;
}
 
@Directive({
  selector: '[appFeatureFlag]',
  standalone: false,
})
export class AppFeatureFlagDirective implements OnChanges {
  private readonly viewContainer = inject(ViewContainerRef);
 
  private readonly template = inject(TemplateRef<unknown>);
 
  private readonly store = inject(Store<IFeatureAccessState>);
 
  @Input() public appFeatureFlag?: string | null;
 
  public ngOnChanges(changes: IInputChanges) {
    const value: string | null | undefined = changes.appFeatureFlag.currentValue;
    if (value === null) {
      this.viewContainer.createEmbeddedView(this.template);
      return;
    }
    const featureSelector =
      typeof value === 'undefined' || value === '' ? featureAccessSelector.enable : featureAccessSelector.enableFeature(value);
    void this.store
      .select(featureSelector)
      .pipe(
        tap(flagValue => {
          if (flagValue) {
            this.viewContainer.createEmbeddedView(this.template);
          }
        }),
      )
      .subscribe();
  }
}