[英]Why Angular 2+ structural directive doesn't update the view?
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.在我的应用程序中,我有一个具有权限数组的帐户服务,因此我创建了一个结构指令来决定是否显示操作的按钮,但问题是当我登录/注销并更新权限数组时,该指令没有t 更新视图。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.