Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngIf not updating DOM

I have a variable isLTEavailable in my ts file inside a function. When the function is called, based on the a condition, isLTEavailable's value changes and is logged correctly, but for some reason, it is not being updated in the DOM.

Here's my ngif condition:

<li class="nav-item dropdown" *ngIf="isLTEavailable">

Here's my ts function:

console.log("Lte --", lte_id)

if (lte_id != undefined) {
    sessionStorage.setItem("lte_customer_id", lte_id.toString())
    this.isLTEavailable = true;
    console.log("isLTEavailable -----> ", this.isLTEavailable)
} else {
    sessionStorage.setItem("lte_customer_id", 'n/a')
    this.isLTEavailable = false;
    console.log("isLTEavailable -----> ", this.isLTEavailable)    
}

I printed the variable using string interpolation as well and it always shows true as its value even though console updates correctly.

P.S. isLTEavailable is initialized as true.

like image 235
Ujjwal Sharma Avatar asked Oct 19 '25 04:10

Ujjwal Sharma


2 Answers

According to this

Change detection fails on change in a variable inside a callback or subscribe method. One could use

 ngZone.run(() => { this.isLTEavailable = false }) 

to update the value. (or) trigger the change detection manually by following

import {ChangeDetectorRef} from '@angular/core'
constructor(private ref: ChangeDetectorRef){}


//after variable update
this.ref.detectChanges();

Let me know if this works. Thanks

like image 52
Mukundhan Avatar answered Oct 21 '25 18:10

Mukundhan


Make Use of Angular's Observable

In your TS file :

Declare :

  import { Observable } from 'rxjs';
  isLTEavailable : Observable<boolean> ; 

  //and in your function
  console.log("Lte --", lte_id)

  if (lte_id != undefined) {
    sessionStorage.setItem("lte_customer_id", lte_id.toString())
    this.isLTEavailable = new Observable(observer=>observer.next(true));
  } else {
    sessionStorage.setItem("lte_customer_id", 'n/a')
    this.isLTEavailable = new Observable(observer=>observer.next(false));
  }

Then in your HTML Use the ASYNC pipe :

 <li class="nav-item dropdown" *ngIf="isLTEavailable | async">

Here is the working example i have put together for you to look at :

https://stackblitz.com/edit/angular-v4dvx6

like image 24
Wisely D Cruizer Avatar answered Oct 21 '25 18:10

Wisely D Cruizer



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!