Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boolean value in Angular2 viewmodel does not update *ngIf template

I have a weird behavior I need some help with. This is an angular2 and typescript app.

I have a template that contains the following html which uses ngIf:

<div *ngIf="loading" class="row">
        <div class="small-3 small-centered columns"  >
            <img src="/Images/loading_spinner.gif" />
        </div>
    </div>

I have a button that triggers a function to change the value of loading

export class ShiftEditComponent implements OnInit {

    loading: boolean = false;

    setLoading(value: boolean): void {
        if (this.loading !== value) {
            this.loading = !this.loading;
        }
    }
}

Here is the weird thing. If i specify the value of the value parameter from somewhere else in the class, the template does not update. BUT if I strip out the logic and just assign loading to its opposite, then it works and the template updates and the ngIf shows and does not show accordingly.

THIS WORKS:

    setLoading(): void {
            this.loading = !this.loading;
    }

QUESTION: Why does this work and ngIf updates when i just assign the opposite value, but if I try to specify the value through a parameter the ngIf template does not update(show or hide)

like image 631
J King Avatar asked Apr 20 '16 04:04

J King


1 Answers

If i specify the value of the value parameter from somewhere else in the class, the template does not update

A common symptom that you have the wrong this in that handler

Fix

Use an arrow function https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

like image 70
basarat Avatar answered Sep 20 '22 23:09

basarat