我需要根据当前用户的服务或权限隐藏或显示链接。我可以通过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);
}
}
答案 0 :(得分:2)
这意味着
*ngIf="(services$ | async)?.SPECIAL_FEATURE === false"
如果条件为真,则显示
虽然这意味着
[hidden]="(services$ | async)?.SPECIAL_FEATURE === false"
如果条件为真,则隐藏它。
他们是彼此的对立面,这就是为什么它不起作用&#34;。
编辑您编辑了问题以将ngIf设置为true,因此我在堆栈上对其进行了测试,我认为我遇到了您的问题。
在隐藏条件下,测试SPECIAL_FEATURE
的值是否等于false。
这意味着
仅当特殊功能变量等于false时才隐藏内容。
但是,这并不涵盖undefined
或null
值,例如虚假值。
Try this :
[hidden]="!(services$ | async)?.SPECIAL_FEATURE"