Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 not re-rendering until I click the page?

On this page here.

It's possible to see that the Facebook login button is initially disabled. (Using [disabled]="myProperty")

Once an API request /facebooklogin/isnewuser returns, it is enabled.

Everything works fine. However, the button won't be re-rendered until I click on the page.

I've also noticed that this happens with most things involving the data-binder in Angular.

  • Is this intended behavior?
  • Is there anyway around this?
  • Is this specific to Angular?

Tested on Firefox & Chrome

like image 226
williamsandonz Avatar asked May 20 '26 16:05

williamsandonz


1 Answers

It seems that for some reason change detection isn't happening as it should. You can "force" it with NgZone or manually trigger change detection with ChangeDetectorRef:

import { ChangeDetectorRef } from '@angular/core' 

constructor(private ref: ChangeDetectorRef) {}

and then run detectChanges() after setting your variable:

// whatever you are using to disable/enable button
this.myProperty = false;
this.ref.detectChanges();

or the use of NgZone:

import { NgZone } from '@angular/core' 

constructor(private ngZone: NgZone) {}

and add something like the following where you are enabling the button:

// whatever you are using to disable/enable button
this.ngZone.run(() => {this.myProperty = false})

I can't say anything more to as why this is happening. I have noticed that once in while these things happen for no apparent reason, this seems to be one of those cases. If anyone has some insight on this, please do tell. Haven't come upon anyone who has been able to explain this, yet :)

like image 129
AT82 Avatar answered May 22 '26 06:05

AT82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!