Yifan
Yifan

Reputation: 376

Why is my *ngIf detecting an object is not empty (Angular2)?

In my.component.ts, I have this part in my template

<li><a *ngIf="m_userO=={}" [routerLink]="['LoginPage']">Login</a></li>
<li><a *ngIf="m_userO!={}" (click)="logOut(m_userO)">{{m_userO.first_name}}<br>Logout</a></li>

and I export

export class myComponent{
m_userO : userO = {};
}

In the loginPage.component.ts, I import myComponent and when they press login, this happens

myComponent.m_userO = this.x_userO; 

where I've confirmed x_userO is not empty at this point.

The idea is that if they're not logged in, it will say "Login" and if they are, it will say "Logout". The problem is when I load the website, it's already showing "Logout" but I'm not sure why. Thanks.

Upvotes: 0

Views: 1699

Answers (1)

Try let the instance undefined or null if the user isn't logged and then when he logges create the instance. After this compare the instances like this:

<li><a *ngIf="m_userO" [routerLink]="['LoginPage']">Login</a></li>
<li><a *ngIf="!m_userO" (click)="logOut(m_userO)">{{m_userO.first_name}}<br>Logout</a></li>

Upvotes: 2

Related Questions