Search code examples
angularangular2-routingangular4-router

How to recall component controller in Angular 4 for the same route link?


I have got two routing links:

/article/1
/article/2

These links are related with the same component:

{path: 'article/:id', component: HomeComponent}

When component is initialized, then after click over link /article/2 it does not initialize this component again.

How to fix?

HTML is:

 <div (click)="setCurrentRole(role)" *ngFor="let item of menuService.getMenuItems(role)"><a
                [routerLink]="[item.url]" (click)="setActiveLink(i, item.url)" [routerLinkActive]="['is-active']">{{item.title
                | translate}}</a></div>

Solution

  • To reload a component :

    In your component, on the init hook, subscribe to routing events, and move your init code into a function

    constructor(private route: ActivatedRoute) {}
    
    ngOnInit() {
      this.route.params.subscribe(params => {
        console.log(params['id']);
        this.doOnInit();
      });
    }
    
    doOnInit() {
      // your old code here
    }
    

    Subscribing to router events :

    constructor(private router: Router) {}
    
    ngOnInit() {
      this.router.events.subscribe(events => {
        // Several routing events, take only the last one
        if (events instanceof NavigationEnd || events.constructor.name === NavigationEnd.name) {
          console.log(params['id']);
          this.doOnInit();
        }
      });
    }
    
    doOnInit() {
      // your old code here
    }