作为ng-if的指令(Angular 2)
发布时间:2020-12-17 09:57:31 所属栏目:安全 来源:网络整理
导读:我正在尝试创建一个作为ngIf的指令来控制具有正确权限的用户是否允许查看特定内容,如下所示: div [type-of-user]="load data from the user and check it (normal or premium)" h3You are allow to see this./h3/div 我正在阅读关于如何做到这一点并在doc上
我正在尝试创建一个作为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(); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |