0

I am probably overseeing something, but I am stuck, the following variables do not seem to be updating in the template when their values are updated in the promise:

private emailDetected: boolean = false;
private detectedEmail: string = "";

detectEmailViaPassword() {
    this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider()).then(authResult => {
        this.detectedEmail = authResult.user.email;
        this.emailDetected = true;
    }).catch(error => {
        console.log(error);
    });
}

When logging the variables, it seems that they are updated, but nothing is happening in the template. When I update the variables from somewhere else than the firebase auth promise, it works correctly -- I am extremely confused...

The variables are referred to correctly in the template: {{ detectedEmail }}

I would be very thankful for some help :)

Cryptic Pug
  • 527
  • 4
  • 19
  • If I remember this correctly, setting the variables as `private` that means they cannot be accessible in the template. This indicate that they are private to the `class` typescript file. – Andrew Lobban Aug 01 '18 at 13:35

2 Answers2

1

Hello the access of your variable is private your have to change to public if do you want to access directly from the template, if not you will need to return using a function or something public in the template.

rojaswilmer
  • 120
  • 4
1

(Assuming .signInWithPopup is a web-request, or other asynchronous call)

Angular change detection runs in response to use interaction with the component. If values are updated outside of that event handling, you need to manually tell the component that it has changed.

constructor(private changeDetector: ChangeDetectorRef){}

detectEmailViaPassword() {
    this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider()).then(authResult => {
        this.detectedEmail = authResult.user.email;
        this.emailDetected = true;
        this.changeDetector.markForCheck();
    }).catch(error => {
        console.log(error);
    });
}

More in depth reading: https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html


Addressing the public vs private comments:

These type descriptors are TypeScript language constructs. Once the TypeScript is compiled into JavaScript, they have no bearing on how the application functions. The TypeScript compiler can only detect access errors from other TypeScript - access from the template is (effectively) unrestricted.

Additional Discussion: "private" and "public" in Angular 2 component

Vlad274
  • 6,514
  • 2
  • 32
  • 44
  • Hello @Vlad274, Thank You Very much for your answer. This definitely lead me into the right direction. I didn't know this Change Detection / Template Rendering Stuff was even existing ;)... very helpful. Not quite sure why, but .markForCheck() did not work for me, instead I use `this.changeDetector.detectChanges()`. – Cryptic Pug Aug 01 '18 at 16:59