18

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.

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
Daniel Soublett
  • 849
  • 2
  • 8
  • 23
  • if you are looking for `if` condition you are trying to re invent the wheel .. check [*ngIf](https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngIf) – Suraj Rao Apr 20 '17 at 11:03
  • directives are used to modify user content, so try to inject some content to directive and modify it. – Roman C Apr 20 '17 at 11:07
  • Thanks for your advices, at the end I could make it just editing a plunkr I found about directives and an awesome article. @RomanC – Daniel Soublett Apr 20 '17 at 12:45
  • [Here](http://stackoverflow.com/a/43492590/573032) some round-trips about directives – Roman C Apr 20 '17 at 12:50

2 Answers2

25

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();
    }

  }

}
Daniel Soublett
  • 849
  • 2
  • 8
  • 23
  • You may find this article useful as well [Exploring Angular DOM manipulation techniques using ViewContainerRef](https://blog.angularindepth.com/exploring-angular-dom-abstractions-80b3ebcfc02) – Max Koretskyi Sep 18 '17 at 06:13
6

The accepted answer doesn't use angular's *ngIf implementation.

I've written a custom *ngIf directive that uses it: http://avenshteinohad.blogspot.com/2018/06/custom-ngif-directive.html

ohadinho
  • 6,894
  • 16
  • 71
  • 124