0

I have a simple component with a property userFirstName.

Now I just want to display this property. I have made a simple binding, and I initialize the userFirstName in the constructor but it works only when there it is the first command!

So this works fine: and it shows the "User Name" text.

this.userFirstName = "User Name";
this.loggedIn = localStorage.getItem("currentUser")!=null;
var currentUser = localStorage.getItem('currentUser');
let user:User = JSON.parse(currentUser) ;
this.userFirstName = localStorage.getItem('currentUser');

Now if I put this.userFirstName = "User Name"; at the last, it doesn't work.

So this doesn't work and it shows empty string!

   this.loggedIn = localStorage.getItem("currentUser")!=null;
    var currentUser = localStorage.getItem('currentUser');
    let user:User = JSON.parse(currentUser) ;
    this.userFirstName = localStorage.getItem('currentUser');
    this.userFirstName = "User Name";

Here is the corresponding html:

<div>
     <a >Hello  {{userFirstName}} ! </a>
//some content
</div>
developer033
  • 24,267
  • 8
  • 82
  • 108
Bakri Bitar
  • 1,543
  • 18
  • 29

1 Answers1

1

Since DOM is loaded faster, it will not wait for the response from the localStorage, so you will get that issue.

Fix :

Method 1 : Using *ngIf

<div *ngIf="userFirstName"> ... </div>

This will load the DOM only if there is a value in the userFirstName

Method 2 : Making the service calls in the constructor()

constructor(){
    this.loggedIn = localStorage.getItem("currentUser")!=null;
    var currentUser = localStorage.getItem('currentUser');
    let user:User = JSON.parse(currentUser) ;
    this.userFirstName = localStorage.getItem('currentUser');
}

Method 3 : Initializing the variable with a empty string during declaration itself.

userFirstName = "";
Aravind
  • 40,391
  • 16
  • 91
  • 110