Directive that works as ng-if (Angular 2)
Asked Answered
C

2

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.

Carpeting answered 20/4, 2017 at 11:0 Comment(4)
if you are looking for if condition you are trying to re invent the wheel .. check *ngIfScandal
directives are used to modify user content, so try to inject some content to directive and modify it.Perlis
Thanks for your advices, at the end I could make it just editing a plunkr I found about directives and an awesome article. @RomanCCarpeting
Here some round-trips about directivesPerlis
C
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();
    }

  }

}
Carpeting answered 20/4, 2017 at 12:49 Comment(1)
You may find this article useful as well Exploring Angular DOM manipulation techniques using ViewContainerRefAlcoholic
A
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

Adabelle answered 9/8, 2018 at 12:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.