Search code examples
angularangular-directiveangular14

How directives can prevent a component to construct?


So I'm trying to create a directive that would work with feature flags, not sure if my idea is going in the right direction but what I want to achieve is to have logic that decides if a component should load or not, and make my entire app to follow my directive as a development-policy.

I created a directive that receives a flagName and a value, can be used like this:

<div featureFlagCheck flagName='componentVersion' flagValue='v1'>
 <app-comp1>..
</div>

The directive code will check if the flag v1 is current or not, and act accordingly, no issues there, but let's say the current flag value is "2", so the entire DIV should not be shown.

I'm trying this:

    this.elementHref.nativeElement.style.display = 'none';

The component is hidden, but the problem is that this statement does not prevents CONSTRUCTOR of my app-comp1 to load, If the directive says you are not up, then it should not even load.

I know this can be made by using *ngIf like this example below, the ngIf prevents the constructor to load:

<div *ngIf="checkFlagIs('v1')">

anybody can point me what could be ngIf doing internally to prevent component to load?


Solution

  • If you want to do smth like *ngIf -- you can just copy-paste code from angular source https://github.com/angular/angular/blob/12.1.x/packages/common/src/directives/ng_if.ts, just change directive inputs and remove unneeded code like ngIfElse.

    Another way is to extend directive class, smth like:

    class Feature extends NgIf implements OnChanges {
      @Input() feauture;
      @Input() feautureValue;
    
      ngOnChanges() {
        this.ngIf = this.feautureFactory.checkValue(this.feature, this.featureValue)
      }
    }
    
    <div *feature="myName" [featureValue]="someValue"></div>