angularangular2-routingangular-routerangular19

Multiple <router-outlet> Angular 19


I have a page where I display a material table with a select drop-down to select a category from multiple categories and a search box to filter the table.

I want to give each category in the drop-down with its own URL, so if the user selects, for example category "c", the URL will become something like "/home/c"

and the table shows just the records that belong to c

so I created a component to only display the table

and in the parent component, I did something like:

<div>
<form [formGroup]="myForm">
    <!-- Search area -->
 <div>
  <mat-form-field>
    <mat-label>I'm looking for</mat-label>
    <mat-select formControlName="selectedCategory">
      @for (category of categoryTypes; track category) {
        <mat-option [value]="category">{{ category }}</mat-option>
      }
    </mat-select>
  </mat-form-field>
 </div>
 <!-- *********** -->

 <!-- Table -->
  <div>
    <mat-form-field>
        <mat-label>Filter</mat-label>
        <input matInput (keyup)="applyFilter($event)" placeholder="Ex. OMB" #input>
      </mat-form-field>
      <router-outlet name="abc"></router-outlet>

Then in the component:

ngOnInit(): void {
  this.myForm.valueChanges.subscribe(value => {
  this.router.navigate(['selectedCategory']);
  this.dataSource.data = ...;
})

And this is my routes array:

export const routes: Routes = [{
  path: '',
  redirectTo: '/home',
  pathMatch: 'full'
}, {
  path: '',
  component: HomePageComponent,
  title: 'abc',
  children: [
    {
        path: 'home',
        component: ...
    }, {
        path: 'xyz',
        component: xyzComponent
    }, {
        path: 'selectedCategory',
        component: selectedCategoryComponent,
        outlet: 'abc'
    }
  ]
},  {
  path: '...,

But every time I select a category from the drop-down, I get the following error:

ERROR RuntimeError: NG04002: Cannot match any routes. URL Segment: 'selectedCategory'

What's the issue?

Thanks


Solution

  • You are not navigating correctly for the auxiliary route, it should be:

    this.router.navigate(['', { outlets: { abc: ['selectedCategory'] } }]);
    

    Reference: Auxiliary Routes in Angular