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.
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.
To get started, we need to create a new Angular project. You can do this by running the following command in your terminal:
ng new my-appNow, let's navigate to the project directory:
cd my-appTo use router links, we first need to create components and their corresponding routing modules. Let's create two components: HomeComponent and AboutComponent.
ng generate component home
ng generate component aboutAfter creating the components, we need to modify the app-routing.module.ts file to include routes for our components:
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 { }Now, let's add router links to our components. In the home.component.html file, we'll add a link to the about component:
<a routerLink="/about">About Us</a>In the about.component.html file, we'll add a link back to the home component:
<a routerLink="/">Home</a>We can now run our application by running the following command in the terminal:
ng serveOpen 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.
What is the directive used in Angular to navigate between different components or sections of an application?
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! 🎉