Router Link in Angular Tutorial 🎯

beginner
17 min

Router Link in Angular Tutorial 🎯

Welcome to the Router Link lesson in Angular! In this tutorial, we'll learn how to navigate between components using router links. By the end of this lesson, you'll be able to create a multi-page application and understand how routing works in Angular.

What is Router Link in Angular? 📝

Router Link is a directive used in Angular to navigate between different components or sections of an application. It allows us to create a user-friendly interface by providing clickable links to various pages within our application.

Setting up a new Angular project 💡

To get started, we need to create a new Angular project. You can do this by running the following command in your terminal:

bash
ng new my-app

Now, let's navigate to the project directory:

bash
cd my-app

Creating components and routing modules 📝

To use router links, we first need to create components and their corresponding routing modules. Let's create two components: HomeComponent and AboutComponent.

bash
ng generate component home ng generate component about

After creating the components, we need to modify the app-routing.module.ts file to include routes for our components:

typescript
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule { }

Adding Router Link to our components 💡

Now, let's add router links to our components. In the home.component.html file, we'll add a link to the about component:

html
<a routerLink="/about">About Us</a>

In the about.component.html file, we'll add a link back to the home component:

html
<a routerLink="/">Home</a>

Running the application ✅

We can now run our application by running the following command in the terminal:

bash
ng serve

Open your browser and navigate to http://localhost:4200/. You should see a link called "About Us". Click on it, and you'll be redirected to the about component.

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the directive used in Angular to navigate between different components or sections of an application?

Conclusion 📝

In this lesson, we learned how to use router links in Angular to navigate between components. By understanding how routing works in Angular, we can create multi-page applications with ease.

In the next lesson, we'll dive deeper into Angular routing and learn how to pass data between components using routes. Stay tuned! 🎉