Angular 14 function inside callback value not updating view
I've written a function, inside of which I'm calling a callback function. After the callback answer, I updated a string variable, but my view was not updated.
Old Code
import { Component, HostListener, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-appointment',
templateUrl: './appointment.component.html',
styleUrls: ['./appointment.component.css']
})
export class ViewComponent {
getAddress : string;
public totlaBalance : string;
ngOnInit():void{
var self = this;
fetchData(this.getEmployees,function(error,res){
console.log(res);
self.totlaBalance = res;
});
}
}
Solution 1 (new Code):
Just need to use ArrowFunction (()=>) and call the method ChangeDetectionRef as shown below,
import { ChangeDetectorRef, Component, HostListener, OnInit, } from '@angular/core';
@Component({
selector: 'app-appointment',
templateUrl: './appointment.component.html',
styleUrls: ['./appointment.component.css']
})
export class ViewComponent {
getAddress : string;
public totlaBalance : string;
constructor(private ref: ChangeDetectorRef){}
ngOnInit():void{
var self = this;
fetchData(this.getEmployees,function(error,res){
console.log(res);
self.totlaBalance = res;
self.ref.detectChanges();
});
}
}
Solution 2: NgZone
An injectable service for executing work inside or outside of the Angular zone.
The most common use of this service is to optimize performance when starting a work consisting of one or more asynchronous tasks that don't require UI updates or error handling to be handled by Angular. Such tasks can be kicked off via runOutsideAngular and if needed, these tasks can reenter the Angular zone via run.
constructor(private _ngZone: NgZone) {}
// Loop outside of the Angular zone
// so the UI DOES NOT refresh after each setTimeout cycle
processOutsideOfAngularZone() {
this.label = 'outside';
this.progress = 0;
this._ngZone.runOutsideAngular(() => {
this._increaseProgress(() => {
// reenter the Angular zone and display done
this._ngZone.run(() => { console.log('Outside Done!'); });
});
});
}
Comments
Post a Comment