Refresh Angular Component Data Manually to Reflect in the View
Environment
Product | Progress® Kendo UI® for Angular |
Description
How can I manually refresh the data of a Kendo UI for Angular component and update the view with the respective changes?
Solution
There are scenarios where you might need to refresh the data of a Kendo UI for Angular component manually and encounter an issue with the view not reflecting the respective changes. This especially happens when dealing with asynchronous operations or operations outside Angular's zone.
To update the view when refreshing the data of a Kendo UI for Angular component, trigger the Angular change detection mechanism. Change detection is a process by which Angular checks the state of your application and updates the view accordingly to reflect the current state. This mechanism lets you visualize the changes of a component’s properties in the view.
The next five examples show various ways to manually trigger change detection in Angular. All examples in the list below use the following sample data:
interface Person {
name: string;
}
public data: Person[] = [{ name: 'John' }, { name: 'Jane' }];
-
JavaScript spread syntax or
slice()
method—either of these approaches can be used for updating the data array reference for the respective Kendo UI for Angular component, which triggers the change detection process:tspublic updateData(): void { this.data[0].name = "New name"; this.data = [...this.data]; //or the slice() method //this.data = this.data.slice(); }
-
Angular Signals—a signal is a wrapper around a value, which is capable of notifying interested consumers when that value changes. In the context of Kendo UI for Angular, the data of a component can be wrapped in a
signal
and theupdate()
method can be used to update the value of thatsignal
:tspublic data = signal<Person[]>([{ name: 'John' }, { name: 'Jane' }]); public updateData(): void { this.data.update((items) => { items[0].name = "New name"; return items; }); }
-
NgZone.run()
—executes the code in the passed callback function inside the Angular zone, which means that all changes will be identified by the change detection:tsconstructor(private zone: NgZone){} public updateData(): void { this.zone.run(() => { this.data[0].name = "New name"; }); }
-
ChangeDetectorRef.detectChanges()
—performs change detection in the current view and all of its child views:tsconstructor(private cdr: ChangeDetectorRef){} public updateData(): void { this.data[0].name = "New name"; this.cdr.detectChanges(); }
-
ApplicationRef.tick()
—this method runs the change detection process on the view tree of the full component starting from the root view:tsconstructor(private appRef: ApplicationRef){} public updateData(): void { this.data[0].name = "New name"; this.appRef.tick(); }