微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

作为ng-if的指令(Angular 2)

我正在尝试创建一个作为ngIf的指令来控制具有正确权限的用户是否允许查看特定内容,如下所示:
<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上找到关于“属性指令”但我仍然无法实现它(我是Angular 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中添加了该指令.

任何建议如何进行将是伟大的.

经过一些更多的研究,我找到了一个很好的文档,关于如何构建自定义指令,特别是我需要的方式,作为ngIf指令.你可以阅读它 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();
    }

  }

}

原文地址:https://www.jb51.cc/angularjs/140354.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐