Angular 角度指令不工作,指令不更改元素显示
我已经检查了文档和联机帮助,但没有任何效果。由于我不能从指令中使用console.log(请原谅我的新奇之处),我不知道如何测试它或检查它是否正常工作 我的意图是根据用户的角色显示/隐藏元素。我传递每个元素允许的角色。然后检查指令中当前用户的角色是否与传递的任何角色匹配Angular 角度指令不工作,指令不更改元素显示,angular,directive,Angular,Directive,我已经检查了文档和联机帮助,但没有任何效果。由于我不能从指令中使用console.log(请原谅我的新奇之处),我不知道如何测试它或检查它是否正常工作 我的意图是根据用户的角色显示/隐藏元素。我传递每个元素允许的角色。然后检查指令中当前用户的角色是否与传递的任何角色匹配 <div IfRole="office,shop">hi</div> //In the directive, it should transform this string into an array o
<div IfRole="office,shop">hi</div> //In the directive, it should transform this string into an array of roles
hi//在指令中,它应该将该字符串转换为角色数组
import{AfterContentInit,Directive,ElementRef,Input}来自“@angular/core”;
从“./services/auth.service”导入{AuthService};
从“@angular/core”导入{OnInit,TemplateRef,ViewContainerRef};
从“./models/user”导入{UserI};
从“@angular/compiler”导入{IfStmt}”;
从“操作系统”导入{type};
@指示({
选择器:“[IfRole]”
})
导出类元素RoledDirective{
UserRoles:string[];
用户:UserI;
@Input()设置IfRole(角色:字符串){
this.UserRoles=roles.split(“,”);
}
公共构造函数(
二等兵el:ElementRef,
私有templateRef:templateRef,
私有AuthService:AuthService,
私有viewContainer:ViewContainerRef
) {
this.AuthService.currentUser.subscribe(数据=>{
用户=数据;
});
如果(!this.UserRoles.includes(this.User.role))
this.viewContainer.clear();
否则{
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
ngOnInit(){}
}
试试这个
this.AuthService.currentUser.subscribe(data => {
this.User = data;
if (!this.UserRoles.includes(this.User.role))
this.viewContainer.clear();
else {
this.viewContainer.createEmbeddedView(this.templateRef);
}
});
我已经将异步代码放在回调中,现在应该在适当的时候处理它同样的事情,“hi”总是出现。不管我经过什么地方。
this.AuthService.currentUser.subscribe(data => {
this.User = data;
if (!this.UserRoles.includes(this.User.role))
this.viewContainer.clear();
else {
this.viewContainer.createEmbeddedView(this.templateRef);
}
});