我有需要根据当前用户的服务或权限隐藏或显示的链接。我可以通过 Observable 对象访问这些服务,并希望在我的模板中使用它来确定要隐藏/显示的内容。
我注意到这适用于 *ngIf 但不适用于 [hidden] 指令。我找不到任何有关原因的信息?
示例:
@Component({
selector: 'my-app',
template: `
<a href="" *ngIf="(services$ | async)?.SPECIAL_FEATURE === true">
Save dropdown</a>
<a href="" [hidden]="(services$ | async)?.SPECIAL_FEATURE === false">
[Hidden] search</a>
<a href="" [hidden]="hideOtherLink">
The other link</a>
`
})
export class AppComponent implements OnInit {
name = 'Angular 5';
hideOtherLink = false;
services$: Observable<object>;
ngOnInit() {
this.services$ = Observable.timer(2000)
.map(() => {
return {
SPECIAL_FEATURE: true,
SPECIAL_THING: true
}
});
setTimeout(() => {
this.hideOtherLink = true;
}, 2000);
}
}
最佳答案
你对那里的条件感到困惑。
这个的意思
*ngIf="(services$ | async)?.SPECIAL_FEATURE === false"
If the condition is true, then show it
虽然这意味着
[hidden]="(services$ | async)?.SPECIAL_FEATURE === false"
If the condition is true, then hide it.
它们彼此相反,这就是为什么它“不起作用”。
编辑您编辑了您的问题以将 ngIf 设置为 true,所以我在堆栈上测试了它,我想我得到了您的问题。
在隐藏条件下,您测试 SPECIAL_FEATURE
的值是否为等于假。
这意味着
hide the content only if the special feature variable is equal to false.
但这并不包括 undefined
或null
例如,值是假值。
<强> Try this 强>:
[hidden]="!(services$ | async)?.SPECIAL_FEATURE"
关于javascript - Angular2 - 为什么异步变量不能与 [hidden] 指令一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48377650/