gpt4 book ai didi

angular - 为什么 Angular 2+ 结构指令不更新 View ?

转载 作者:行者123 更新时间:2023-12-05 07:37:20 25 4
gpt4 key购买 nike

在我的应用程序中,我有一个具有权限数组的帐户服务,所以我创建了一个结构指令来决定是否显示操作按钮,但问题是当我登录/注销并更新权限数组时,指令不会更新 View 。

代码如下:

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
) { }

}

这是指令用法的示例:

<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();
}

}

关于angular - 为什么 Angular 2+ 结构指令不更新 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48622301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com