Refresh an Angular Component without reloading the same Component

A short trick for refreshing data in the same Angular components. This snippet will work in Angular 2, 4, 5, 6, 7, 8, and 9.

Here two method and  you can add according to your needs

you are working with Angular and need to refresh a component without navigation on another component without using  window.location.reload()  or
 location.reload(),  you can use the following code in your project:

1. using constructor in the same page(component)


reload: any;


Then, add this code to the required component's constructor.

this.router.routeReuseStrategy.shouldReuseRoute = function () {
  return false;
};
this.mySubscription = this.router.events.subscribe((event) => {
  if (event instanceof NavigationEnd) {
    // Trick the Router into believing it's last link wasn't previously loaded
    this.router.navigated = false;
  }
});


Make sure to unsubscribe  from this mySubscription  in  ngOnDestroy().

ngOnDestroy() {
  if (this.mySubscription) {
    this.mySubscription.unsubscribe();
  }
}

Here, we just trick the router into believing that the last link was never visited; when the button is clicked, the program will load that component (refreshing the component).
2. using your router you can use this modal window when you want create, edit component then use it 
I will show my own code for your help, here my component client list card  Your actualComponent['clients/'] name and I want open a modal window for create a client RefreshComponent['clients/create'] or you can put same url RefreshComponent['/'] both are work,  like this after your modal window dismiss then put it and here  '/clients/create' modal window routing and 'clients/' my component where you want get the data without page refresh 

this.router.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
    this.router.navigate(['Your actualComponent']);
}); 

This snippet will work in Angular 2, 4, 5, 6, 7, 8 and 9.
#without #refresh  #window #angular #component

Comments

Popular posts from this blog

.NET Core vs .NET Framework: How to Pick a .NET Runtime for an Application

multi color initial(Avatars) if img not available in Angular it's work angular 2,4+ all versions