Search code examples
javascripthtmlangularangular6angular-ng-if

Variable change detection does not seem to be working with ngIf


I have already tried things in posts similar to mine, but still can't seem to get this working. I want to show something on my webpage after about 15 seconds. I use setTimout and then an if statment to check if something is true or not and then change a Boolean variable accordingly.

I have a component that has a variable timer which I originally set to false. Then I run the the setTimeout in a function. After 15 seconds I make a check. I then change the timer variable, if needed. This did not work. So then I also added a router.navigate back to my page thinking it would reevaluate the timer variable, but this also did not work.

This is my html

<br> <br>
<div *ngIf="timer == false">
  <p>Results are loading. Please wait.</p>
  <div>
  <div *ngIf="timer == true">
    <p>Sorry, but this seems to be taking longer than usual. Please wait while we continue to check.</p>
    </div>
 <br>
 <div class="spinner">
  <div class="bounce1"></div>
  <div class="bounce2"></div>
  <div class="bounce3"></div>

</div>

Then inside my component

constructor(private _apiService: ApiService, private router: Router, private _dataService: DataService)
    {}
    public timer: boolean = false;

checkDuplicates(someArray){
        var count = 0;
        var i = 0;
        var length = this.userResults.length;

        setTimeout(() => {
                    if(length != someArray.length){
                        this.timer = true;
                        this.router.navigate(['/processing'])
                        console.log('turn on new processing notification')
                    }

                }, 15000)

As of now I am getting the "Results are loading. Please wait.", but even when the timer variable is switched to true no change. I tried this with and without the router.navigate. I have tried all of the things listed below with now luck. I have also tried doing a manual update by doing ChangeDetectionRef and NgZone and ApplicationRef methods mentioned in other posts. Could I please get some insight.


Solution

  • I could not get this working using ngIf. Instead I formatted the html to have an id tab and then I used document.getElementById and changed it in the setTimeout function.