3

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.component.html',
    styleUrls: ['./navbar.component.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?

10
  • 1
    @Vega no. That's a bad suggestion Commented Aug 23, 2017 at 11:26
  • What's the problem with the current code? Commented Aug 23, 2017 at 11:27
  • What is inside the user object? you can view it in the html by using {{user | json}} or just console.log it. Commented Aug 23, 2017 at 11:27
  • Seems like you snippet is incomplete. How are you injecting localStorage? Post some more relevant code Commented Aug 23, 2017 at 11:28
  • @dag sessionStorage and localStorage is globally available... Commented Aug 23, 2017 at 11:28

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. But my question is how i can set variable with value before html render, since i want to use it's value in my template.
Since this is a binding, it will update in your template when the user variable changes in your typescript. So initially, user might be null and nothing will show in the <p>, but it will update after you set user. This seems like the right answer.
3

After proper searching, found my answer here.

Angular2: How to load data before rendering the component?

@Wesley Coetzee, thanks for your support.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.