我创建了一个指令,根据用户声明显示或隐藏组件。
是允许的。directive.ts
import { Directive, TemplateRef, ViewContainerRef, Input, Output, EventEmitter } from '@angular/core';
import { SecurityService } from 'app/_security/security.service';
@Directive({
selector: '[appIsAllowed]'
})
export class IsAllowedDirective {
@Output() isReady = new EventEmitter<boolean>();
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private ss: SecurityService,
) { }
@Input('appIsAllowed') set isAllowed(claimType: any) {
if (this.ss.hasClaim(claimType)) {
this.viewContainer.createEmbeddedView(this.templateRef);
this.notAllowed(false);
} else {
this.notAllowed(false);
this.viewContainer.clear();
}
}
notAllowed(isAllowed: boolean) {
debugger;
this.isReady.emit(isAllowed);
}
}
然后我有两个组成部分。1是管理模板组件,另一个是示例组件。
管理模板组件.html
<ng-container *ngIf="sampleToUpdate">
<app-sample *appIsAllowed="'Admin'" (isReady)="notifyIfAllowed($event)" [sampleData]="sampleToUpdate"></app-sample>
</ng-container>
管理模板组件
notifyIfAllowed($event: boolean) {
debugger;
if (!$event) {
this.toastr.error('You are not allowed to do this operation', 'Unauthorized', {
closeButton: true,
progressBar: true,
timeOut: 3000
});
}
}
样本组件
@Input() sampleData: SampleData;
constructor() { }
ngOnInit(): void {
console.log(this.sampleData);
}
一切似乎都按照指令中的预期工作,但不知何故,父组件的
notifyIfAllowed()
没有被调用,因为它没有到达断点。我试图实现的是;什么时候
<app-sample>
由于以下原因无法显示
claims
这在
directive
我需要一个祝酒词来通知用户。