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?

DreamTeK
  • 32,537
  • 27
  • 112
  • 171
parth
  • 624
  • 1
  • 10
  • 29

2 Answers2

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.

Martin
  • 15,820
  • 4
  • 47
  • 56
Wesley Coetzee
  • 4,768
  • 3
  • 27
  • 45
  • 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. – parth Aug 23 '17 at 12:56
  • 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 `

    `, but it will update after you set `user`. This seems like the right answer.

    – rmc00 Aug 23 '17 at 14:05
3

After proper searching, found my answer here.

Angular2: How to load data before rendering the component?

@Wesley Coetzee, thanks for your support.

parth
  • 624
  • 1
  • 10
  • 29