Here when I login to my app, i want to get json object stored in local Storage and then assign it to user Object. First time if I login it won't show anything but if I refresh the page I can see first name.
Here is .ts file
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-navbar',
templateUrl: './navbarponent.html',
styleUrls: ['./navbarponent.css']
})
export class NavbarComponent implements OnInit {
user: Object;
ngOnInit() {
this.user = JSON.parse(localStorage.getItem('user'));
}
}
And in template I want to use it like this:
<p> {{ user.first_name }} </p>
How can i solve this?
Here when I login to my app, i want to get json object stored in local Storage and then assign it to user Object. First time if I login it won't show anything but if I refresh the page I can see first name.
Here is .ts file
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.ponent.html',
styleUrls: ['./navbar.ponent.css']
})
export class NavbarComponent implements OnInit {
user: Object;
ngOnInit() {
this.user = JSON.parse(localStorage.getItem('user'));
}
}
And in template I want to use it like this:
<p> {{ user.first_name }} </p>
How can i solve this?
localStorage
? Post some more relevant code
– DAG
Commented
Aug 23, 2017 at 11:28
Your html is rendering before the variable is being set
Inside your html use this:
<p> {{ user?.first_name }} </p>
This is called the Safe Navigation Operator which will prevent the error and render the first_name
when it is populated.
After proper searching, found my answer here.
Angular2: How to load data before rendering the ponent?
@Wesley Coetzee, thanks for your support.