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

in html i warning should only be displayed when an error occurs, e.g. 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 great. but when I set the value from observable, ngIf does not get the updated value.

Here's a simplified code that always sets the error to true for testing purposes

 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 should call?

+6
source share
2 answers

You can try if this fixes your problem:

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

If so, there is code in this.service.createProject(this.model) that calls execution, leaving a corner zone.

Update

You do not need this if you use ()=> everywhere instead of function () , and if you do not pass functions only by name, for example someFunc(mycallback) , but instead with someFunc(() => mycallback()) or someFunc(mycallback.bind(this))

+8
source

An error has been detected. this changes. in observable, this indicates a more limited function for the component.

so I need to get the component reference to a variable and set the error in this link to true.

working code is as follows:

 var component = this; this.service.createProject(this.model).subscribe(i=>{ component.error = true; 
0
source

Source: https://habr.com/ru/post/1012579/


All Articles