Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - *ngif not refreshing when variable update from oberservable subscribe

in the html i have warning should only be shown when a error state occurs like thius

<div class="alert alert-danger" *ngIf="error">
    <strong>Not saved!</strong> There was an error when saving the project. Please try again later.
</div>

this works fine. but when I set the value from a observable the ngIf doesn't get the updated value.

Here the simplified code which always sets error to true for testing purposses

export class createProjectComponent {
    constructor(private service:ProjectsService){

    }

    model = new myModel();
    error = false;
    submitForm(){    
        this.service.createProject(this.model).subscribe(i=>{
            this.error=true;
          }
    }

is there some kind of notification i have to trigger?

like image 330
Boas Enkler Avatar asked Nov 23 '16 08:11

Boas Enkler


2 Answers

You can try if this fixes your issue:

constructor(private cdRef:ChangeDetectorRef) {}

submitForm(){    
    this.service.createProject(this.model).subscribe(i=>{
        this.error=true;
        this.cdRef.detectChanges();
    }
}

If it does there is some code in this.service.createProject(this.model) that causes execution leaving Angulars zone.

update

You don't need this if you use ()=> everywhere instead of function () and if you don't pass functions just by name like someFunc(mycallback) but instead with someFunc(() => mycallback()) or someFunc(mycallback.bind(this))

like image 74
Günter Zöchbauer Avatar answered Nov 12 '22 01:11

Günter Zöchbauer


Found the error. the this changes . in the observe this points to the osbervable not anymore to the component.

so I have to get a reference of the component to a variable and set error on this reference to true.

working code looks like this:

var component = this;

this.service.createProject(this.model).subscribe(i=>{
                component.error = true;
like image 24
Boas Enkler Avatar answered Nov 12 '22 02:11

Boas Enkler