All files / src/app/core/directives feature-toggle.directive.ts

100% Statements 23/23
86.95% Branches 20/23
100% Functions 5/5
100% Lines 23/23

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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65223x 223x 223x 223x   223x                                       223x   156x 156x     156x 156x 156x 156x   156x   312x             267x 267x 87x 180x 24x   267x         156x       31x 31x      
import { ChangeDetectorRef, Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { BehaviorSubject, combineLatest, of } from 'rxjs';
import { distinctUntilChanged, switchMap } from 'rxjs/operators';
 
import { FeatureToggleService, FeatureToggleType } from 'ish-core/feature-toggle.module';
 
/**
 * Structural directive.
 * Used on an element, this element will only be rendered if the specified feature *is enabled*.
 *
 * For the negated case see {@link NotFeatureToggleDirective}.
 * For the corresponding pipe see {@link FeatureTogglePipe}.
 *
 * @example
 * <div *ishFeature="'quoting'; else disabledTemplate">
 *   Only visible when quoting is enabled.
 * </div>
 * <ng-template #disabledTemplate>
 *   <div>Quoting is disabled.</div>
 * </ng-template>
 */
@Directive({
  selector: '[ishFeature]',
})
export class FeatureToggleDirective {
  private otherTemplateRef: TemplateRef<unknown>;
  private feature$ = new BehaviorSubject<'always' | 'never' | FeatureToggleType>(undefined);
  private elseSet$ = new BehaviorSubject<boolean>(false);
 
  constructor(
    private templateRef: TemplateRef<unknown>,
    private viewContainer: ViewContainerRef,
    private featureToggle: FeatureToggleService,
    private cdRef: ChangeDetectorRef
  ) {
    combineLatest([
      this.feature$.pipe(
        switchMap(feature => (feature ? this.featureToggle.enabled$(feature) : of(false))),
        distinctUntilChanged()
      ),
      this.elseSet$,
    ])
      .pipe(takeUntilDestroyed())
      .subscribe(([enabled, elseSet]) => {
        this.viewContainer.clear();
        if (enabled) {
          this.viewContainer.createEmbeddedView(this.templateRef);
        } else if (elseSet && this.otherTemplateRef) {
          this.viewContainer.createEmbeddedView(this.otherTemplateRef);
        }
        this.cdRef.markForCheck();
      });
  }
 
  @Input() set ishFeature(feature: 'always' | 'never' | FeatureToggleType) {
    this.feature$.next(feature);
  }
 
  @Input() set ishFeatureElse(otherTemplateRef: TemplateRef<unknown>) {
    this.otherTemplateRef = otherTemplateRef;
    this.elseSet$.next(true);
  }
}