如何检测绑定到另一个 object 属性 的 object 属性 的变化?
How to detect change of object property which bind to another object property?
我有很多导航项。当用户有适当的规则时,每个导航应该是可见的。我尝试做一些事情:
我的 object 其中包含一些规则:
rules: {
canSeeProfile: true,
canSeeAdminZone: false,
...
}
我还有一组导航项:
nav: [
{title: 'profile', visible: this.rules.canSeeProfile},
{title: 'admin zone', visible: this.rules.canSeeAdminZone && this.rules.canSeeProfile},
...
]
我的 header 包含以下模板:
<ng-template *ngFor="let navItem of nav">
<li *ngIf=navItem.visible>
{{navItem.title}}
</li>
</ng-template>
但是 *ngIf 在 rules
变量更改时不更新:
hideProfile() {
this.rules.canSeeProfile = false;
}
如何在不重新初始化 nav
数组的情况下更新模板?或者,也许有更好的解决方案?谢谢!
只需用函数替换您的值:
nav: [
{title: 'profile', visible: () => this.rules.canSeeProfile},
{title: 'admin zone', visible: () => this.rules.canSeeAdminZone && this.rules.canSeeProfile},
...
]
然后使用
<li *ngIf="navItem.visible()">
或者,如果您希望它稍微更有效(但更冗长),则在每次规则更改时发出一个事件,并重新计算存储在 nav
.
中的每个可见值
我有很多导航项。当用户有适当的规则时,每个导航应该是可见的。我尝试做一些事情:
我的 object 其中包含一些规则:
rules: {
canSeeProfile: true,
canSeeAdminZone: false,
...
}
我还有一组导航项:
nav: [
{title: 'profile', visible: this.rules.canSeeProfile},
{title: 'admin zone', visible: this.rules.canSeeAdminZone && this.rules.canSeeProfile},
...
]
我的 header 包含以下模板:
<ng-template *ngFor="let navItem of nav">
<li *ngIf=navItem.visible>
{{navItem.title}}
</li>
</ng-template>
但是 *ngIf 在 rules
变量更改时不更新:
hideProfile() {
this.rules.canSeeProfile = false;
}
如何在不重新初始化 nav
数组的情况下更新模板?或者,也许有更好的解决方案?谢谢!
只需用函数替换您的值:
nav: [
{title: 'profile', visible: () => this.rules.canSeeProfile},
{title: 'admin zone', visible: () => this.rules.canSeeAdminZone && this.rules.canSeeProfile},
...
]
然后使用
<li *ngIf="navItem.visible()">
或者,如果您希望它稍微更有效(但更冗长),则在每次规则更改时发出一个事件,并重新计算存储在 nav
.