Ad

Can't Display Variable Data In HTML - Angular 8

I am trying to display the username of a logged in user in my HTML. I am using firebase for authentication purposes and Angular 8 for the main development. Firebase integration is fully supported and causes no problems. But when I try to display the data fetched from firebase user name, I can't do so.

I have done a lot of Google searches, including reading the Angular CLI documentation and also looking at various previous questions asked on stackoverflow but I can't seem to figure it, somehow. This is my code:

export class PortalComponent implements OnInit {

  public username: string = null;

  constructor() {

    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.username = user.displayName;
      }
    });

  }
}

And this is my HTML code:

<h2>Welcome {{username}}!</h2>

How do I fix this? My expected answer should be something like Welcome Brian!

EDIT:

I looked at a lot of answers and most of them are correct implementations, however I am not sure why this is not working. I am still looking for answers with complete angular implementation but for the moment I used jQuery and it works. What I did:

Updated HTML:

<h2>Welcome <span id="username"></span>!</h2>

Updated TypeScript:

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';

// Code removed for brevity

export class PortalComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        $('#username').html(user.displayName);
      }
    });
  }

}

Ad

Answer

Since I'm assuming you will be adding more than a Username in the future I recommend you tweak your code to use a service. I works the same way but is more flexible when working with larger data.

user.service.ts:

 export class UserService {
   constructor() {}
   username: string;

   getUsername() {
     return this.username;
   }
   setUsername(user) {
     this.username = user;
   }
}

Your component Updated:

 export class PortalComponent implements OnInit {

   username: string; //Setting null is unnecessary 
   userService: UserService;
   constructor(private _userService: UserService) {
     this.userService= _userService;
     firebase.auth().onAuthStateChanged((user) => {
       if (user) {
         this.userService.setUsername(user);
       }
     });
   }
   get GetUsername(): string
   {
     return this.userService.getUsername();
   }
}

Componenent html:

 <div *ngIf="this.GetUsername()">
   <h2>Welcome{{ this.GetUsername() }}!</h2>
 </div>
Ad
source: stackoverflow.com
Ad