Angular 6 Routing Simple Working Example

·

Angular 6 Routing Simple Working Example

Hello to all, welcome to therichpost.com.  In this post, I am going to tell, Angular 6 Routing Simple Working Example.

Here is the working picture:

Angular-6-routing

Here is the code and need to add the Angular 6 application for routing:

1. Very first, please make two new component for routing process and please run below commands for creating new angular components into your terminal:
ng g component aboutus

ng g component contantus
 You can see below new folders, after run above command:

Angular-6-components

 
2. After that, Here is the code for app.module.ts file:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Routes, RouterModule } from '@angular/router';
import { AboutusComponent } from './aboutus/aboutus.component';
import { ContantusComponent } from './contantus/contantus.component';

const appRoutes: Routes = [
    { path: 'aboutus', component: AboutusComponent },
  { path: 'contactus', component: ContantusComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    AboutusComponent,
    ContantusComponent
  ],
  imports: [
    BrowserModule,
  BrowserAnimationsModule, 
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )	
  ],
  entryComponents: [AppComponent],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

3. After that, here is the code for app.component.html file:
<div class="jumbotron text-center">
  <h1>Angular 6 Routing Example</h1>
</div>
<nav class="navbar navbar-expand-sm bg-light">
  <ul class="nav nav-pills">
    <li class="nav-item"><a class="nav-link" routerLink="/aboutus">About Us</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="/contactus">Contact Us</a></li>
  </ul>
</nav>
<br>

<div class="container-fluid">
<h3><router-outlet></router-outlet></h3>
</div>

 And that is it and this is very easy and everyone can do this. 

If have any query related to this post, then please so ask questions or comment below.

Comments

4 responses to “Angular 6 Routing Simple Working Example”

  1. sam Avatar
    sam

    Thank you for awesome post.

  2. Ajay Malhotra Avatar

    Your most welcome Sam.

  3. David Avatar
    David

    Good Post and helpful..

  4. Ajay Malhotra Avatar