angularangular8angular-routerangular-router-events

Angular reloading component does not work


I am just trying to reload the component without refreshing the page.

Here is the code for that:

import { Component, VERSION, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router'

@Component({
  selector: 'my-home',
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit  {

  name = 'Angular ' + VERSION.major;
  time = new Date().getSeconds();

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

    this.router.routeReuseStrategy.shouldReuseRoute = () => false;

    this.time = new Date().getSeconds(); //updating the time on load.
  }

  ngOnInit(){
    console.log('iniit');
  }
}

In my html I have a button to reload the component by navigating to the url again. Please advice if I am wrong

<hello name="{{ name }}" time="{{time}}"></hello>
<p>
  Start editing to see some magic happen :) {{time}}
</p>

<a [routerLink]="['/home']">Go to Home </a>

When I click on the button, it is supposed to update the time because of the component reload. But whenever I click on the link, no update happens on the time.

Can anyone advice me how to reload the component when we need without reloading my window (window reload kills my auth info).

Live demo


Solution

  • so problem is that angular know you are routing to the same page you are on. So first of all you have to tell angular to reload when you route to the same route you are on.

    Like this:

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

    Then you have to tell angular if you want to always run you route guards. (optional)

    {
      path:"home",
      component: HomeComponent,
      ... your guards ...
      runGuardsAndResolvers: "always",
    }
    

    And there is more to it, but here if you need.

    Demo: https://stackblitz.com/edit/angular-ivy-g29jum?file=src%2Fapp%2Fapp.route.module.ts