[Fixed] Is there a way to switch two components in routing?



  selector: 'app-driver-details',
  templateUrl: './driver-details.component.html',
  styleUrls: ['./driver-details.component.css']
export class DriverDetailsComponent implements OnInit {

  id!: number;
  driver!: Driver;
  constructor(private route: ActivatedRoute, private driverService: DriverService) { }

  ngOnInit(): void {
    this.id = this.route.snapshot.params["id"];
    this.driver = new Driver();
    this.driverService.getDriverById(this.id).subscribe(data =>{
      this.driver = data;


const routes: Routes = [
  {path: 'drivers', component: DriverListComponent},
  {path: 'driver-details/:id', component: DriverDetailsComponent},
  {path: '', redirectTo: 'drivers', pathMatch: 'full'}

  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
export class AppRoutingModule { }


@CrossOrigin(origins = "http://localhost:4200")
public class DriverController {

    private DriverRepository driverRepository;

    public List<Driver> getAllDrivers(){
        return driverRepository.findAll();

    public ResponseEntity<Driver> getDriverById(@PathVariable Long id) {
        Driver driver = driverRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Driver not exist with id :" + id));
        return ResponseEntity.ok(driver);

So currently my routing is working the following way: I can reach a driver’s details with the following path: localhost:4200/driver-details/id

But, I would need the other way around, so like this: localhost:4200/id/driver-details

I tried to "switch" the order like this: {path: ‘:id/driver-details’, component: DriverDetailsComponent},
but unfortunately that wasn’t the solution.

enter image description here


You can do this by using child routes:

const routes: Routes = [
        path: 'drivers',
        component: DriverListComponent
        path: 'driver',
        children: [
                path: ':id',
                children: [
                        path: '', 
                        redirectTo: 'driver-details',  
                        pathMatch: 'full'
                        path: 'driver-details',
                        component: DriverDetailsComponent

By calling ‘localhost:4200/driver/6/driver-details’, the ‘DriverDetailsComponent’ will be called.

You can find more information on these type of routes here.

Leave a Reply

(*) Required, Your email will not be published