[angular] How to Refresh a Component in Angular

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.

This question is related to angular routes components refresh

The answer is


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.


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

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

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


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

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

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


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


One more way without explicit route:

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

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.


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

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
  }

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

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"]);

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

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to routes

How to open a link in new tab using angular? How to Refresh a Component in Angular laravel Unable to prepare route ... for serialization. Uses Closure How to use router.navigateByUrl and router.navigate in Angular No provider for Router? Difference between [routerLink] and routerLink How to force Laravel Project to use HTTPS for all routes? Change route params without reloading in Angular 2 Angular 2 router no base href set How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

Examples related to components

How to Refresh a Component in Angular Angular 4 - get input value Disable Button in Angular 2 How to Pass data from child to parent component Angular How to map an array of objects in React Checking for Undefined In React What's the difference between an Angular component and module React component initialize state from props How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime React - how to pass state to another component

Examples related to refresh

How to Refresh a Component in Angular Angular + Material - How to refresh a data source (mat-table) How to Update a Component without refreshing full page - Angular How to reload page the page with pagination in Angular 2? Swift: Reload a View Controller Button that refreshes the page on click Update data on a page without refreshing How to refresh or show immediately in datagridview after inserting? Gradle project refresh failed after Android Studio update Refresh Part of Page (div)