2016-08-16 12 views
2

ngIfの状態で私を助けることができる人は、キーが存在しないときにログアウトを隠そうとしていて、localStorageに存在するときにそれを表示しようとしています。私はngIfの複数の条件について混乱していますが、小切手は正しいです。angular2 ngIf真偽条件

このチェックは指令として使用されています。

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> 

答えて

3

それはあなたが何をしたいようだ

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

あるローカル変数はテンプレートで使用できなくなります。テンプレートは、コンポーネントクラスの最上位のプロパティとメソッドにのみ直接アクセスできます。

+0

html行が外部テンプレートとしてではなくコンポーネント内にある場合でも、私は参照してください?しかし、HTMLのチェックは正しいですか?代わりにthis.showLogoutを追加する必要がありますか? – nCore

+0

テンプレートが 'template:" ... "または' templateUrl: 'として追加された場合、pathToTemplate"は何の違いもありません。メソッドにローカル変数( 'checkSession')を宣言すると、メソッドの実行が完了すると変数はもう存在しません。 –

+0

私はあなたの '* ngIf'までは見ていませんでした。単に '* ngIf =" showLogout "や' * ngIf = "!showLogout" 'はあなたが何を望むかによって十分です。 'this.showLogout'のデフォルト値を設定することができます(私はその答えを更新します)。 –