Dan*_*ett 11 typescript angular2-directives angular
我正在尝试创建一个作为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>
我正在阅读有关如何做到这一点,并在本文档中找到"属性指令",但我仍然无法实现它(我是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中添加了该指令.
任何建议如何进行将是伟大的.
Dan*_*ett 14
经过一些更多的研究,我找到了一个很好的文档,关于如何构建自定义指令,特别是我需要的方式,作为ngIf指令.你可以在这里阅读它,并在这里看到plunkr
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();
    }
  }
}
可接受的答案不使用angular的*ngIf实现。
我已经编写了一个*ngIf使用它的自定义指令:http :
 //avenshteinohad.blogspot.com/2018/06/custom-ngif-directive.html
| 归档时间: | 
 | 
| 查看次数: | 5168 次 | 
| 最近记录: |