简体   繁体   English

Angular2-为什么异步变量不能与[hidden]指令一起使用?

[英]Angular2 - why doesn't async variable work with [hidden] directive?

I have links that I need to hide or show based on the services to or permissions of the current user. 根据当前用户的服务或权限,我需要隐藏或显示链接。 I have these services accessible via an Observable object and was hoping to use it in my template to determine what to hide/show. 我可以通过Observable对象访问这些服务,并希望在我的模板中使用它们来确定隐藏/显示的内容。

I noticed though that this works for *ngIf but not for the [hidden] directive. 我注意到尽管这适用于* ngIf,但不适用于[hidden]指令。 I can't find any info on why this is? 我找不到有关为什么的任何信息?

Example: 例:

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

} 

You got confused in your conditions there. 您在那里的状况感到困惑。

This one means 这意味着

*ngIf="(services$ | async)?.SPECIAL_FEATURE === false"

If the condition is true, then show it 如果条件为真,则显示它

While this one means 虽然这意味着

[hidden]="(services$ | async)?.SPECIAL_FEATURE === false"

If the condition is true, then hide it. 如果条件为真,则将其隐藏。

They are the opposit of each other, that's why it is "not working". 它们彼此相对,这就是为什么它“不起作用”的原因。

EDIT You edited your question to set the ngIf to true, So I tested it on stack and I think I got your issue. 编辑您编辑了您的问题以将ngIf设置为true,所以我在堆栈上对其进行了测试,我认为您遇到了问题。

In your hidden condition, you test if the value of SPECIAL_FEATURE is equal to false. 在隐藏状态下,您测试SPECIAL_FEATURE的值是否等于false。

This means 这意味着

hide the content only if the special feature variable is equal to false. 仅当特殊功能变量等于false时才隐藏内容。

But this doesn't cover the undefined or null values, for instance, which are falsy values. 但这不包括undefinednull值,例如, 虚假值。

Try this : 试试这个

[hidden]="!(services$ | async)?.SPECIAL_FEATURE"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM