How to Refresh a Component in Angular

AngularRoutesComponentsRefresh

Angular Problem Overview


I am working on an Angular project. I'm struggling with refresh action in a component.

I would like to refresh the router's components on button click. I have refresh button when I click on it the component/router need to be refresh.

I tried window.location.reload() and location.reload() these two are not suitable for my need. Please help if anyone aware of it.

Angular Solutions


Solution 1 - Angular

After some research and modifying my code as below, the script worked for me. I just added the condition:

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

Solution 2 - Angular

Use the this.ngOnInit(); to reload the same component instead reloading the entire page!!

DeleteEmployee(id:number)
  {
    this.employeeService.deleteEmployee(id)
    .subscribe( 
      (data) =>{
        console.log(data);

        this.ngOnInit();

      }),
      err => {
        console.log("Error");
      }   
  }

Solution 3 - Angular

Adding this to code to the required component's constructor worked for me.

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();
  }
}

Refer to this thread for more details - https://github.com/angular/angular/issues/13831

Solution 4 - Angular

Fortunately, if you are using Angular 5.1+, you do not need to implement a hack anymore as native support has been added. You just need to set onSameUrlNavigation to 'reload' in the RouterModule options :

@ngModule({
 imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
 exports: [RouterModule],
 })

More information can be found here: https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

Solution 5 - Angular

this is little bit out of box and I dont know whether this helps you or not but have yo tried

this.ngOnInit();

its a function so whatever code you have in it will be recalled just like a refresh.

Solution 6 - Angular

One more way without explicit route:

async reload(url: string): Promise<boolean> {
  await this.router.navigateByUrl('.', { skipLocationChange: true });
  return this.router.navigateByUrl(url);
}

Solution 7 - Angular

Just follow the below steps:

  1. add {onSameUrlNavigation: 'reload'} as below in your app-routing.modules.ts

> @NgModule({
> imports: [ RouterModule.forRoot(routes,{onSameUrlNavigation: 'reload'})],
> exports: [ RouterModule ]
> })

  1. add this.router.routeReuseStrategy.shouldReuseRoute = () => false as below in you component ts file constructor: > > > > constructor(private router: Router) { > this.router.routeReuseStrategy.shouldReuseRoute = () => false; > }
  2. Now click the button and call ajax server call, get the desired data from server and replace your global variable in TS file with new data.
  3. call this.router.navigate([/sameRoute]); in the last. replace sameRoute with your route url.

  4. make sure to return false at the end in your refresh button's onClick method, otherwise it will lead to main routing page instead of same page reload.

    These steps will reload your page. :)

For more details: https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

I am using Angular 12.

Solution 8 - Angular

This can be achieved via a hack, Navigate to some sample component and then navigate to the component that you want to reload.

this.router.navigateByUrl('/SampleComponent', { skipLocationChange: true });
this.router.navigate(["yourLandingComponent"]);

Solution 9 - Angular

There are problems with some of the answers before:

  1. one should not call lifecycle methods such as ngOnInit() directly.
  2. re-navigating to some URL is a sub-optimal solution, especially if the component you are dynamically loading is only a small part of a big page

This worked for me (I don't know if it is recommendable or optimal)

  1. In the component to be dynamically loaded, add a public reference to the ChangeDetectorRef.
  2. I assume that the dynamically loaded data has some input data, ("tags" in the example), which is updated after the fact and is creating rendering problems.
  @Input()
  tags: string[] = [];

  constructor(public changeDetector: ChangeDetectorRef )
  1. In the parent component doing the dynamic loading, after having created the child component dynamically and maybe set some data to it, call the created instance's changeDetector.markForCheck() as follows:
  constructor(private vcrf: ViewContainerRef, private cfr: ComponentFactoryResolver, private elementRef: ElementRef) {
  }

  public loadComponent(): void {

    const componentFactory = this.cfr.resolveComponentFactory(TagsListComponent);
    const component = this.container.createComponent(componentFactory);
    component.instance.tags = /* whatever data we want to pass */;
    component.instance.changeDetector.markForCheck();
    ...

loadComponent() is a custom function that could be called, for example, once the parent page scrolls to some position in the parent component, indicating that the dynamic component should be shown.

Solution 10 - Angular

In my application i have component and all data is coming from API which i am calling in Component's constructor. There is button by which i am updating my page data. on button click i have save data in back end and refresh data. So to reload/refresh the component - as per my requirement - is only to refresh the data. if this is also your requirement then use the same code written in constructor of component.

Solution 11 - Angular

Just change the routeReuseStrategy from the angular Router:

this._router.routeReuseStrategy.shouldReuseRoute = function () {
      return false;
    };

Set the routerproperty "navigated" to false:

this._router.navigated = false;

Then navigate to your component:

this._router.navigate(['routeToYourComponent'])

After that reinstate the old/default routeReuseStrategy:

this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
          return future.routeConfig === curr.routeConfig;

You can also make a service out of this:

@Injectable({
  providedIn: 'root'
})
export class RouterService {

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _router: Router
  ) { }

  reuseRoutes(reuse: boolean) {
    if (!reuse) {
      this._router.routeReuseStrategy.shouldReuseRoute = function () {
        return false;
      };
    }
    if (reuse) {
      this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return future.routeConfig === curr.routeConfig;
      };
    }
  }

  async refreshPage(url?: string) {
    this._router.routeReuseStrategy.shouldReuseRoute = function () {
      return false;
    };

    this._router.navigated = false;

    url ? await this._router.navigate([url]) : await this._router.navigate([], { relativeTo: this._activatedRoute });

    this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
      return future.routeConfig === curr.routeConfig;
    };
  }
}

Solution 12 - Angular

kdo

// reload page hack methode

push(uri: string) {
    this.location.replaceState(uri) // force replace and no show change
    await this.router.navigate([uri, { "refresh": (new Date).getTime() }]);
    this.location.replaceState(uri) // replace
  }

Solution 13 - Angular

constructor(private router:Router, private route:ActivatedRoute ) { 
}

onReload(){
 this.router.navigate(['/servers'],{relativeTo:this.route})
}

Solution 14 - Angular

calling ngOnInit() does not work for my complicated component, I end up using this

reloadCurrentRoute() {
    let currentUrl = this.router.url;
    this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
        this.router.navigate([currentUrl]);
    });
}

Solution 15 - Angular

just do this : (for angular 9)

import { Inject } from '@angular/core';    
import { DOCUMENT } from '@angular/common';
    
constructor(@Inject(DOCUMENT) private document: Document){ }

someMethode(){ this.document.location.reload(); }

Solution 16 - Angular

html file

<a (click)= "getcoursedetails(obj.Id)" routerLinkActive="active" class="btn btn-danger">Read more...</a>

ts file

  getcoursedetails(id)
  { 
  this._route.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
    this._route.navigate(["course",id]);
  }); 

Solution 17 - Angular

router.navigate['/path'] will only takes you to the specified path
use router.navigateByUrl('/path')
it reloads the whole page

Solution 18 - Angular

reload () { this.ngOnInit(); }

Solution 19 - Angular

In my case I needed to reload specific routes (not all in the application), so adding the global setting {onSameUrlNavigation: 'reload'} had no effect, while this.router.routeReuseStrategy.shouldReuseRoute = () => false in the component works but modifies the global settings of the router.

The solution was to save the original router configuration to a variable before changing it in the component's constructor as indicated @abhishek-singh by the first answer of the problem.

private routeReuseStrategy:any;

  constructor(
    private router:Router
  ) {
    this.routeReuseStrategy = this.router.routeReuseStrategy.shouldReuseRoute;
    this.router.routeReuseStrategy.shouldReuseRoute = () => false;
  }

And when exiting the path, remap the original configuration using the OnDestroy hook.

   public ngOnDestroy():void
   {
     this.router.routeReuseStrategy.shouldReuseRoute = this.routeReuseStrategy;
   }

Solution 20 - Angular

Other way to refresh (hard way) a page in angular 2 like this it's look like f5

import { Location } from '@angular/common';

constructor(private location: Location) {}

pageRefresh() {
   location.reload();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSreehari BallampalliView Question on Stackoverflow
Solution 1 - AngularSreehari BallampalliView Answer on Stackoverflow
Solution 2 - AngularShinoy BabuView Answer on Stackoverflow
Solution 3 - AngularsankarView Answer on Stackoverflow
Solution 4 - AngularLucian MoldovanView Answer on Stackoverflow
Solution 5 - AngularVadapalli ChaituView Answer on Stackoverflow
Solution 6 - AngularFelixView Answer on Stackoverflow
Solution 7 - AngularAbhishek SinghView Answer on Stackoverflow
Solution 8 - AngularSajeetharanView Answer on Stackoverflow
Solution 9 - AngularGonzalo Robert DíazView Answer on Stackoverflow
Solution 10 - AngularBh00shanView Answer on Stackoverflow
Solution 11 - AngularTombalabombaView Answer on Stackoverflow
Solution 12 - AngularJulien RoussetView Answer on Stackoverflow
Solution 13 - AngularBehzad BehzadView Answer on Stackoverflow
Solution 14 - AngularFeng ZhangView Answer on Stackoverflow
Solution 15 - AngularReza PiriView Answer on Stackoverflow
Solution 16 - AngularHarishanker MauryaView Answer on Stackoverflow
Solution 17 - AngularHarpreet SinghView Answer on Stackoverflow
Solution 18 - AngularAnis KCHAOUView Answer on Stackoverflow
Solution 19 - AngularJuan CastilloView Answer on Stackoverflow
Solution 20 - Angularchirag sorathiyaView Answer on Stackoverflow