NgIf not updating when variable changes NgIf not updating when variable changes angular angular

NgIf not updating when variable changes


A good way is to share data through reactive coding with Observable.

In your service, create a BehaviorSubject and its Observable:

private _isAuthenticatedSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);public isAuthenticatedObs: Observable<boolean> = _isAuthenticatedSubject.asObservable();

Each time you want to update your value, do a next on your subject:

_isAuthenticatedSubject.next(true); // authenticated_isAuthenticatedSubject.next(false); // no more

Component side, just subscribe the observable to set the value locally for every subject changes:

this.authService.isAuthenticatedObs.subscribe(isAuth => this.isAuth = isAuth);

Or display value in your template with async pipe:

<ng-template *ngIf = "authService.isAuthenticatedObs | async">


The problem is that you are providing the service at component level, that means, that all your components, that have the service added to providers array in component will have their own instance of service, so this is not a shared service at all. You want to have a singleton service, so only set the service in your providers array in your ngModule.

Also like mentioned by others, calling methods in template is a really bad idea, this method is called on each change detection, which is often, so it really hurts the performance of the app.

You could use Observables like suggested, or then just have a shared variable in your service. In the long run I'd suggest Observables, but depending on case just a shared variable is alright. Here's a sample for both: Passing data into "router-outlet" child components (angular 2)


template should be

<ng-template *ngIf = "authService.isAuthenticated()">