2017-04-20 97 views
5

我试图创建一个ngIf工程控制指令,如果用正确的权限的用户被允许看到具体的内容,这样的事情:指令,它作为NG-IF(角2)

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

我读到有关如何做到这一点,并在此doc关于“属性指令”,但我仍然无法实现它发现(我是新与角2)

到目前为止,我有这样的:

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

} 

我已经在app.module中添加了指令。

任何意见如何继续将是伟大的。

+0

..检查[* ngIf](https://angular.io/ docs/ts/latest/guide/template-syntax.html#!#ngIf) –

+0

指令用于修改用户内容,所以尝试向指令注入一些内容并对其进行修改。 –

+0

感谢您的建议,最后我可以编辑一下我发现的有关指令和文章的plunkr。 @RomanC –

回答

3

经过一些研究,我发现了一个关于如何构建自定义指令的好文档,特别是我需要的方式,它充当ngIf指令。你可以,如果你正在寻找`if`条件你试图重新发明轮子读到它here看看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(); 
    } 

    } 

} 
+0

的一些往返行程您可能也会发现这篇文章很有用[使用ViewContainerRef探索Angular DOM操作技术](https:// blog.angularindepth.com/exploring-angular-dom-abstractions-80b3ebcfc02) –