Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 ngIf true or false condition

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>
like image 447
nCore Avatar asked Sep 12 '26 21:09

nCore


1 Answers

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 components class directly.

like image 135
Günter Zöchbauer Avatar answered Sep 15 '26 11:09

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!