0
votes

So I am trying to use angular over JQuery which is a bit of a mind bender.

In my app I want to change text according to a users logged in state. If he is logged in, I want to show: My Account, and if no one is logged in I want to show: Login / Register.

Easy to do in Jquery, not quite sure the best method for NG.

HTML

<li>
    <a (click)="openLoginForm()">         
    <i class="fa fa-lock"></i> Login / Register</a> 
    <i class="fa fa-lock"></i> My Account</a> 
</li>

What I would like to do is check a variable: loggedIn, if true it shows "My Account", if false it shows "Login / Register".

I am not 100% clear how to do this via Angular2...

3

3 Answers

2
votes

Freshbm's answer is the better solution but i wanted to clarify what happens in {{ isLogged ? "My Account" : "Login / Register" }}

isLogged is usually a boolean of true or false but can be a value

? is a check

"My Account" if the boolean is true or the value is valid

: means if false, undefined or null, do this

"Login / Register" if the boolean is false or the value is null or undefined

2
votes

Something like this, set isLogged when user logs on your component:

<a (click)="openLoginForm()">
    <i class="fa fa-lock"></i> {{ isLogged ? "My Account" : "Login / Register" }}
</a>

This is only working as simple binding, it will not detect change so you could do somthing like this:

<a (click)="openLoginForm()">
        <i class="fa fa-lock"></i> {{ isLoggedTittle }}
    </a>

and in component set the title:

isLoggedTittle = logged ? "My Account" : "Login / Register";
-1
votes

In your situation the ideal solution is to use ngIf:

<li>        
    <a (click)="openLoginForm()" *ngIf="!loggedIn"> 
        <i class="fa fa-lock"></i> Login / Register</a> 
    <a (click)="openMyAccountForm()" *ngIf="loggedIn"> 
        <i class="fa fa-lock"></i> My Account</a> 
</li>

This will show the My Account section if loggedIn is true, and Login/Register if false.

By using two different anchor tags entirely you can completely change how each one behaves, what icon is inside them etc.