7
votes

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)

1
It does update the same. The problem is somewhere else. - Günter Zöchbauer

1 Answers

6
votes

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