Angular default routing with more components?

Viewed 58

Is it possible to route more than one component to the default routing?

My routing module looks like:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BodyComponent } from './body/body.component';
import { ContactComponent } from './contact/contact.component';
import { NavbarComponent} from './navbar/navbar.component';
import { HomeComponent} from './home/home.component';
import { ErrorComponent} from './error/error.component';

const routes: Routes = [
  {
    path: '', component: BodyComponent,
  },
  {
    path: '', component: HomeComponent,
  },
  {
    path: '', component: NavbarComponent,
  },
  {
    path: 'contacts', component: ContactComponent,
  },

  /* Error */
  {
    path: '**', component: ErrorComponent/* Error Component */
  },
  
];

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

My app.component.html looks like:

<app-navbar>
    <app-body></app-body>
    <app-home></app-home>
    <app-contact></app-contact>
    <router-outlet></router-outlet>
    <app-footer></app-footer>
</app-navbar>

For example if I start http://localhost:4200/, all my components should be there with empty path: ''.

But if I open http://localhost:4200/contacts then only the contact components should be open.

Thanks!

2 Answers

My friend I think that you are confuse, when you use routing is one route for each component, otherwise how Angular gonna knows which component to open?. I think that you are trying to use a nav-bar navigator to navigate from one component to other in that case I suggest to use router-outlet. check this

Using *ngIf combined with router can be very useful for showing components depending on the url.

class AppComponent {
    constructor(private router: Router) { }
}

<app-navbar *ngIf="router.url === ''">
    <app-body></app-body>
    <app-home></app-home>
    <app-contact></app-contact>
    <router-outlet></router-outlet>
    <app-footer></app-footer>
</app-navbar>
Related