0

In the following typescript code I have a value moreinfo which I initialize to 1. After that inside the constructor I change the value to 2. So with value 1 I display one div with *ngIf and with value 2 I display a different div. All works perfectly and I see that the value has correctly changed to 2 from console.

export class LoginComponent implements OnInit {
  moreinfo: number=1;
  email: string;
  password: string;

  constructor(public afAuth: AngularFireAuth, public af: 
    AngularFireDatabase,public authService: AuthService) {

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        this.moreinfo=2;
        var user2 = firebase.auth().currentUser;
        console.log("Current user id:" + user2.uid + "\nMoreinfo:" + this.moreinfo);
      } else {
        console.log("No user is signed in."); 
      }
    });
  }
}

However when I compare the value in the HTML it displays the div with morevalue == 1; despite the fact that the value has changed to 2. Is there anyone that can shed some light on my problem?

<div class="container" *ngIf="moreinfo == 1">
  <h1 *ngIf="authService.user | async">Welcome {{ (authService.user | async)?.email }}!</h1>
</div>

<div class="container" *ngIf="moreinfo == 2">
  something
</div>
0mpurdy
  • 3,198
  • 1
  • 19
  • 28
Vasilis Michail
  • 403
  • 2
  • 6
  • 17

1 Answers1

1

I think it is because the closure that you are using is incorrect, instead of an anonymous function, try an arrow function, which should set the value in the component - not just in the function.

Like this:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    this.moreinfo=2;
    var user2 = firebase.auth().currentUser;
    console.log("Current user id:" + user2.uid + "\nMoreinfo:" + this.moreinfo);
  } else {
    console.log("No user is signed in."); 
  }
});
0mpurdy
  • 3,198
  • 1
  • 19
  • 28