我正在尝试创建一个作为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();
}
}
}
接受的答案不使用angular的*ngIf
实现。
我写了一个使用它的自定义*ngIf
指令:http://avenshteinohad.blogspot.com/2018/06/custom-ngif-directive.html