Angular 16 routing; In this tutorial, i am going to show you how to create and use routing in Angular 16 apps.
Angular 16 Routing Tutorial with Example
Use the below given steps to create and use routing in the Angular 16 apps:
- Step 1 – Create New Angular App
- Step 2 – Create Components
- Step 3 – Import Routes in app-routing.module.ts
- Step 4 – Add Router Outlet in View File
- Step 5 – Update Home and Posts Component View
- Step 6 – Start Angular App
Step 1 – Create New Angular App
Run the following command on terminal to install angular app:
ng new my-new-app
Step 2 – Create Components
Run the following command on terminal to create components for routing into your Angular 16 apps:
ng g c home ng g c posts
Step 3 – Import Routes in app-routing.module.ts
Go to src/app/ directory and open the app-routing.module.ts file. Then routes in this file, as follows:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { PostsComponent } from './posts/posts.component'; const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'posts', component: PostsComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Step 4 – Add Router Outlet in View File
Go to src/app directory and open app.component.html file. Then update router outlet code into this file; as follows:
<nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <a class="navbar-brand" href="#">Angular 13 Nested Routing Example - Laratutorials.com</a> <div class="collapse navbar-collapse" id="navbarText"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" routerLink="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/posts">Posts</a> </li> </ul> </div> </nav> <div class="container"> <br/> <router-outlet></router-outlet> </div>
Note that:- In the above form, have used bootstrap 5 classes. if you want to add than then; you can see the following article for that; as follow:
Step 5 – Update Home and Posts Component View
Go to src/app/home/ directory and open home.component.html file. And then add the following code into it; as follow:
<h1>Home Page (HomeComponent)</h1><p>home works!</p>
Next, visit src/app/home/ directory and open posts.component.html file. And then add the following code into it; as follow:
<h1>Posts Page (PostComponent)</h1><p>posts works!</p><a class="btn btn-primary"
Step 6 – Start Angular App
In this step, execute the following command on the terminal to start the angular app:
ng serve
Open browser, enter the below url:
http://localhost:4200
Conclusion
Through this tutorial, You have learned how to create and use routing in Angular 16 apps.