Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
Directive that works as ng-if (Angular 2)

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.

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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

  }

}
about 4 years ago · Santiago Trujillo Denunciar

0

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

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda