我已经检查了文档并在线提供了帮助,但是没有任何效果。由于我无法使用指令中的console.log(请问新颖性如何),我不知道如何对其进行测试或检查其是否正常工作。
我的意图是根据用户的角色显示/隐藏元素。我通过了每个元素允许的角色。然后,它检查指令中当前用户的角色是否与任何传递的角色匹配。
<div IfRole="office,shop">hi</div> //In the directive,it should transform this string into an array of roles
import { AfterContentInit,Directive,ElementRef,Input } from "@angular/core";
import { AuthService } from "../services/auth.service";
import { OnInit,TemplateRef,ViewContainerRef } from "@angular/core";
import { UserI } from "../models/user";
import { IfStmt } from "@angular/compiler";
import { type } from "os";
@Directive({
selector: "[IfRole]"
})
export class ElementsroleDirective {
UserRoles: string[];
User: UserI;
@Input() set IfRole(roles: string) {
this.UserRoles = roles.split(",");
}
public constructor(
private el: ElementRef,private templateRef: TemplateRef<any>,private AuthService: AuthService,private viewContainer: ViewContainerRef
) {
this.AuthService.currentUser.subscribe(data => {
this.User = data;
});
if (!this.UserRoles.includes(this.User.role))
this.viewContainer.clear();
else {
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
ngOnInit() {}
}