2017-04-20 60 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) –