Angular - Routing

The purpose of this article is to explain how routing can be achieved in Angular 4, what Routes are, and how they are rendered on the browser.

Routes

Routes are basically URLs which a user can provide in the browser to request a component. Routes consist of a path and the component:

  1. { path: 'heroChild', component: HeroChildComponent }  
Here, heroChild is the path which the user gives in the URL and HeroChildComponent is the component which gets rendered on the browser.

To implement routes in your project, follow the following steps.

  1. In app.module.ts, import the following component.
    1. import { RouterModule, Routes } from'@angular/router';  
  2. Create routes by providing the path name and component in app.module.ts.
    1. constappRoutes: Routes =  
    2. [  
    3.    { path:'heroChild', component:HeroChildComponent },  
    4.    { path:'heroParent', component:HeroParentComponent },  
    5. ]  
  3. Configure routes in the application using Router Module.
    1. @NgModule({  
    2. declarations: [  
    3.   
    4.    AppComponent,  
    5.    HeroChildComponent,  
    6.    HeroParentComponent,  
    7. ],  
    8. imports: [  
    9.    BrowserModule,  
    10.    FormsModule,  
    11. ReactiveFormsModule,  
    12. RouterModule.forRoot(  
    13.    appRoutes,  
    14. )  
    15. ],  
  4. To render routes, use the router outlet in app.component.html. 
    1. <router-outlet></router-outlet>  
  5. Run your application using ng serve and open "http://localhost:4200/" in your browser. 4200 is the default port for an Angular application. Provide the URL in the browser.

  6. You can also use router link which will act here as an anchor tag and redirect the page to the URL to which they are mapped. Add the below code in app.component.html and run the application.
    1. <h1>Angular Router</h1>  
    2. <nav>  
    3.    <arouterLink="/heroChild"routerLinkActive="active">Child</a>  
    4.    <arouterLink="/heroParent"routerLinkActive="active">Parent</a>  
    5. </nav>  
  7. Open the browser and click on Child or Parent. It will redirect to the component where these are mapped.
I hope this will help!