Directive that works as ng-if (Angular 2)

Daniel Soublett picture Daniel Soublett · Apr 20, 2017 · Viewed 7.6k times · Source

I'm trying to create a directive that works as a ngIf to control if the user with the correct permission is allow to see specific content, something like this:

<div [type-of-user]="load data from the user and check it (normal or premium)">
    <h3>You are allow to see this.</h3>
</div>

I was reading about how to do it and found on this doc about "Attribute Directives" but I still can't implement it (I am new with Angular 2)

So far I have this:

import {Directive, ElementRef, Input} from '@angular/core';

@Directive({
  selector: '[type-of-user]'
})

export class TypeOfUserDirective{

  constructor(private el: ElementRef){}

  @Input('type-of-user') userControl: string;

  private haspermission(permission: string) {
    /*the style background color is just to test if works*/
    this.el.nativeElement.style.backgroundColor = permission;
  }

}

I already added the directive in the app.module.

Any advice how to proceed would be great.

Answer

Daniel Soublett picture Daniel Soublett · Apr 20, 2017

After some more research I found a great doc about how to build custom directives, specifically the way I need, that acts as an ngIf directive. You can read about it here and see the plunkr here

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[isAllow]'
})

export class isAllowDirective {

  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}

  @Input() set isAllow(allow: boolean){
    if (allow) {
      // If condition is true add template to DOM
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
     // Else remove template from DOM
      this.viewContainer.clear();
    }

  }

}