angular 2: Reload same component again when redirect on the same route

21,515

Solution 1

I want, When I click on 'All Events' tab, again and again, events component load every time.

This is Not Possible in angular2, reason is once you load any component that component is only reload once you navigate from another route to that route again.

But you can reload forcefully

Basically there are two methods which are

  • you can call ngOnInit() method again and again as per need, which is not a recommended way

  • you can call one commonn method from ngOnInit() and later as per need call that function again like this

    ngOnInit(){
        this.callingFunction();
    }
    
    forLaterUse(){
        this.callingFunction(); 
    }
    

Another way is if you want to load same component on param change you can use this in constructor

this.route.params.subscribe((params: Params) => {
    console.log(params); 
    this.callingFunction();
    // this will be called every time route changes
    // so you can perform your functionality here

});

Solution 2

This github link below has the right solution https://github.com/angular/angular/issues/13831

Put the below code in the constructor of the component which you want to load

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

this.router.events.subscribe((evt) => {
  if (evt instanceof NavigationEnd) {
    this.router.navigated = false;
    window.scrollTo(0, 0);
  }
});

Solution 3

See here: How to reload the current route with the angular 2 router

To summarize - its not a function that is built into the router. It sounds like the best option is using a service that will refresh or re-fetch any relevant data, and if anything changes, Angular will automatically update the view.

If someone says something is not possible in Angular, that is almost always not true. Its just not possible using currently existing solutions. ;-)

Share:
21,515
Er Vipin Sharma
Author by

Er Vipin Sharma

frontend Developer working on Angular 2 in Noida,India.

Updated on July 20, 2020

Comments

  • Er Vipin Sharma
    Er Vipin Sharma almost 4 years

    I am using 'routerLink' to navigate my routes and it is working fine. But when I click again on the same button, I want that component will load again. But currently, it's not working in angular2.

    app.component.html

    <ul class="nav navbar-nav navbar-right">
                <li><a [routerLink]="['/events']" routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">All Events</a></li>
                <li><a [routerLink]="['/events/new']" routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">Create New</a></li>
    </ul>
    

    I want, When I click on 'All Events' tab, again and again, events component load every time.

    How to achieve this scenario in angular2 ?