最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - angular2 ngIf true or false condition - Stack Overflow

programmeradmin6浏览0评论

Can someone help me with this ngIf condition, I'm trying to hide the logout when key doesn't exist and show it when its exist in the localStorage. I'm getting confused about multiple conditions in the ngIf but the checks are correct.

This check is being used as a directive.

checkSession() {
  var checkKey = localStorage.getItem('sessionKey');
  if(checkKey == null){
      var showLogout = false;
      console.log('null key: ', checkKey);
  } else {
      showLogout = true;
      //this check will only be available once the user is logged in
      console.log('key exist: ' checkKey);
  }

}

Html

 <a (click)="logout()" title="Logout" *ngIf="showLogout || (!showLogout && !showLogout)">
    <i class="fa fa-sign-out fa-2x" aria-hidden="true" ></i>
 </a>

Can someone help me with this ngIf condition, I'm trying to hide the logout when key doesn't exist and show it when its exist in the localStorage. I'm getting confused about multiple conditions in the ngIf but the checks are correct.

This check is being used as a directive.

checkSession() {
  var checkKey = localStorage.getItem('sessionKey');
  if(checkKey == null){
      var showLogout = false;
      console.log('null key: ', checkKey);
  } else {
      showLogout = true;
      //this check will only be available once the user is logged in
      console.log('key exist: ' checkKey);
  }

}

Html

 <a (click)="logout()" title="Logout" *ngIf="showLogout || (!showLogout && !showLogout)">
    <i class="fa fa-sign-out fa-2x" aria-hidden="true" ></i>
 </a>
Share Improve this question edited Aug 16, 2016 at 9:36 Günter Zöchbauer 658k233 gold badges2.1k silver badges1.6k bronze badges asked Aug 16, 2016 at 9:34 nCorenCore 2,0977 gold badges31 silver badges59 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

It seems what you want is

export class MyComponent {

  /// other stuff

  showLogout:boolean = false;

  checkSession() {
    var checkKey = localStorage.getItem('sessionKey');
    if(checkKey == null){
        this.showLogout = false; // changed
        console.log('null key: ', checkKey);
    } else {
        this.showLogout = true; // changed
        //this check will only be available once the user is logged in
        console.log('key exist: ' checkKey);
    }
  }
}

A local variable won't be available in the template. The template can only access top-level properties and methods of your ponents class directly.

发布评论

评论列表(0)

  1. 暂无评论