In my application I have an account service which has permissions array, So I created a structural directive to decide whether showing an action's button or not, but the problem is that when I do login/logout and update the permissions array, the directive doesn't update the view.
here is the code:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { Account } from './models';
import { AccountService } from './account.service';
@Directive({
selector: '[appAuth]',
})
export class AuthDirective {
@Input() set appAuth(action: string) {
if (this._account.permissions.includes(action)) {
this._contRef.createEmbeddedView(this._tmplRef);
} else {
this._contRef.clear();
}
}
constructor(
private _contRef: ViewContainerRef,
private _tmplRef: TemplateRef<any>,
private _account: AccountService
) { }
}
Here is an example of the usage of the directive:
<button
class="btn btn-default"
*appAuth="'find-accounts'"
(click)="doSomething()">
Find Accounts
</button>
import { Account, AccountService } from '../common';
import { Subscription } from 'rxjs/Subscription';
import {
Directive, Input, TemplateRef, ViewContainerRef, OnInit, OnDestroy
} from '@angular/core';
@Directive({
selector: '[appAuth]',
})
export class AuthDirective implements OnInit, OnDestroy {
private _accountChangesSubscription: Subscription;
@Input('appAuth') private appAuth: string;
constructor(
private _contRef: ViewContainerRef,
private _tmplRef: TemplateRef<any>,
private _account: AccountService
) { }
ngOnInit() {
this._accountChangesSubscription = this._account.changes$
.subscribe((account: Account) => {
const permissions = this._account.permissions;
if (permissions && permissions.includes(this.appAuth)) {
this._contRef.createEmbeddedView(this._tmplRef);
} else {
this._contRef.clear();
}
});
}
ngOnDestroy() {
this._accountChangesSubscription.unsubscribe();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.