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:
- { 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.
- In app.module.ts, import the following component.
- import { RouterModule, Routes } from'@angular/router';
- Create routes by providing the path name and component in app.module.ts.
- constappRoutes: Routes =
- [
- { path:'heroChild', component:HeroChildComponent },
- { path:'heroParent', component:HeroParentComponent },
- ]
- Configure routes in the application using Router Module.
- @NgModule({
- declarations: [
-
- AppComponent,
- HeroChildComponent,
- HeroParentComponent,
- ],
- imports: [
- BrowserModule,
- FormsModule,
- ReactiveFormsModule,
- RouterModule.forRoot(
- appRoutes,
- )
- ],
- To render routes, use the router outlet in app.component.html.
- <router-outlet></router-outlet>
- 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.
- 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.
- <h1>Angular Router</h1>
- <nav>
- <arouterLink="/heroChild"routerLinkActive="active">Child</a>
- <arouterLink="/heroParent"routerLinkActive="active">Parent</a>
- </nav>
- Open the browser and click on Child or Parent. It will redirect to the component where these are mapped.
I hope this will help!