Home > front end >  How to show a top level route in Angular named outlet
How to show a top level route in Angular named outlet

Time:10-25

Trivial program below with Angular 12:

  • localhost:4200/a works fine
  • localhost:4200/b gives me the dreaded Cannot match any routes. URL Segment: 'b'
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {RouterModule, Routes} from '@angular/router';

//======================================================================
@Component({
  selector: 'app-root',
  template: `
<ng-container>
  <router-outlet></router-outlet>
  <hr/>
  <router-outlet name="named"></router-outlet>  
</ng-container>`
})
export class AppComponent {
}

//======================================================================
@Component({
  selector: 'a',
  template: 'a here',
})
export class AComponent {
}

//======================================================================
@Component({
  selector: 'b',
  template: 'b here',
})
export class BComponent {
}

//======================================================================
const routes: Routes = [
  {
    component: AComponent,
    path: 'a'
  },
  {
    component: BComponent,
    path: 'b',
    outlet: 'named'
  }
];

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

//======================================================================
@NgModule({
  declarations: [AppComponent, AComponent, BComponent],
  imports: [BrowserModule, AppRoutingModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Worst case, I can push route 'b' down one level (that didn't work either) but I would prefer to keep b at the top level.

Thanks!

CodePudding user response:

Welcome to Stackoverflow @jay :).

You can check here more info https://angular.io/

when you access route B you need to access with router name as its named route. you can use something like localhost:4200/a(named:b)

  • Related