How to use same Component for routing in Angular

Viewed 221

I am using the same component for my router, on the first click the component affected, but on the next click the component still in the first state.

Here is the script for changing the route

<a [routerLink]="['react/1']">link 1</a>
<a [routerLink]="['react/2']">link 2</a>

Here is my router module

panel-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router'
import { PanelCoursesComponent } from 'src/app/components/panel-courses/panel-courses.component';
import { PanelHomeComponent } from 'src/app/components/panel-home/panel-home.component';
import { PanelIntroComponent } from 'src/app/components/panel-intro/panel-intro.component';

const routes: Routes = [
    { path: '', component: PanelHomeComponent },
    { path: 'react', component: PanelIntroComponent },
    { path: 'react/:no', component: PanelCoursesComponent } //the target
]

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class PanelRoutingModule { }

panel-course.component.ts

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

@Component({
  selector: 'app-panel-courses',
  templateUrl: './panel-courses.component.html',
  styleUrls: ['./panel-courses.component.scss']
})
export class PanelCoursesComponent implements OnInit {
  url!: any

  constructor(private route: ActivatedRoute, private router: Router) {
    console.log('route')
  }

  ngOnInit(): void {
    this.url = this.router.url
    console.log(this.route.snapshot.params) //the test script
  }

}

On the PanelCourseComponent I try to console log the params, but that's only executed one time on the first click.

Am I missing something?

2 Answers

You can use this.route.params.subscribe method for this case

Here is the example

ngOnInit(): void {
    this.route.params.subscribe(params => {
      console.log(params) // It will be executed whenever you click the link
    })
  }

by default pathMatch is set to 'prefix'. so paths will be matched against your current location and the first one witch "matches" will render its component. to make your paths match only "exact" match add pathMatch: 'full' for your routes

const routes: Routes = [
    { path: '', component: PanelHomeComponent, pathMatch: 'full' },
    { path: 'react', component: PanelIntroComponent, pathMatch: 'full' },
    { path: 'react/:no', component: PanelCoursesComponent } //the target
]
Related