Search code examples
angularhttpclient

Angular - Display labels without waiting for their value


My component display users'attributes (name, email, ...). I would like to display labels without waiting for their value. I found a solution but I don't like it because I repeat <span *ngIf="user">.

With the following example I immediately display

name: 
email:
...

and 5s later

name:Nicolas 
email:[email protected]
...

user.component.html :

<div>
    name : <span *ngIf="user">{{ user.name }}</span> <br/>
    email : <span *ngIf="user">{{ user.email }}</span> <br/>
    ...
</div>

user.component.ts

export class UserComponent {
  user?: User;

  constructor(private userService: UserapiService) { }

  ngOnInit() {
    // getUser1() calls an API and lasts 5s for example
    this.userService.getUser1().subscribe(user1 => this.user = user1);
  }
}

I don't want the following code because the whole would be displayed 5s later

<div *ngIf="user">
    name : {{ user.name }} <br/>
    email : {{ user.email }}<br/>
    ...
</div>

What is the best solution to display labels without waiting for their value ?

Thanks for your help, Nicolas


Solution

  • Using the Safe Navigation Operator (?.): This operator allows you to access properties on potentially null or undefined objects without causing errors.

    <div>
      name: {{ user?.name }} <br/>
      email: {{ user?.email }} <br/>
      ...
    </div>