Navigating in Angular – Mastering Angular (Part 5)

Posted by


In Angular, routing is a mechanism that helps us navigate between different pages of our application without having to manually reload the entire page. This not only improves the user experience by making the application feel more like a traditional desktop application, but it also makes the application easier to manage and scale.

In this tutorial, we will delve into the basics of routing in Angular. This is the fifth part of our "Learning Angular" series, where we cover various aspects of Angular development in a step-by-step manner.

Setting up a new Angular project:
Before we dive into routing, let’s make sure we have a new Angular project set up. If you haven’t already done so, you can create a new Angular project using the Angular CLI by running the following command:

ng new my-angular-app

Once your project is set up, navigate into the project directory:

cd my-angular-app

Creating a new component:
Next, let’s create a new component that we can use for routing. In this tutorial, we will create a simple component called HomeComponent. To generate a new component, run the following command:

ng generate component home

This will create a new folder called home inside the src/app folder, which contains the necessary files for the HomeComponent.

Setting up routing in Angular:
Angular uses a module called RouterModule to facilitate routing in our application. Before we start using routing, we need to import the RouterModule into our main Angular module (app.module.ts) and configure it with the routes for our application.

In your app.module.ts file, import the RouterModule from @angular/router:

import { RouterModule } from '@angular/router';

Next, define the routes for your application. Create an array of Route objects that represent the different routes in your application. Each Route object should contain a path that defines the URL for the route and a component that should be displayed when the route is activated.

const routes = [
  { path: '', component: HomeComponent },
  // Add more routes here as needed
];

Then, import the routes array and the RouterModule into the imports array of the @NgModule decorator in your app.module.ts file:

@NgModule({
  declarations: [ // Add your components here ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes) // Add this line to enable routing
  ],
  providers: [ // Add your services here ],
  bootstrap: [AppComponent] // Change AppComponent to the root component of your application
})
export class AppModule { }

After setting up routing in your main Angular module, you can start adding links to navigate between different routes in your application. You can add links in your HTML template files using the routerLink directive.

In your HomeComponent component HTML file, add a link to navigate to a new route:

<a routerLink="/about">Go to About</a>

When the user clicks on this link, Angular will navigate to the /about route and display the component associated with that route.

Accessing route parameters:
In many applications, you may need to retrieve data from the URL to fetch specific content or process information. Angular allows us to access route parameters by using the ActivatedRoute service provided by @angular/router.

To access route parameters, inject the ActivatedRoute service into your component and use its snapshot property to access the parameters:

import { ActivatedRoute } from '@angular/router';

export class HomeComponent {
  constructor(private route: ActivatedRoute) {
    const id = this.route.snapshot.params.id;
    console.log(`Route parameter id: ${id}`);
  }
}

In this example, we are retrieving the route parameter with the name id from the URL and logging it to the console.

Handling route changes:
You can also listen for route changes by subscribing to the router events emitted by the Router service provided by @angular/router.

To listen for route changes, inject the Router service into your component and subscribe to the events property:

import { Router, NavigationEnd } from '@angular/router';

export class HomeComponent {
  constructor(private router: Router) {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        console.log('Route changed:', event.url);
      }
    });
  }
}

In this example, we are listening for navigation end events and logging the URL of the new route to the console.

Conclusion:
Routing is an essential feature in Angular applications that allows us to navigate between different parts of our application seamlessly. By following the steps outlined in this tutorial, you can set up routing in your Angular project and start building more dynamic and interactive applications.

I hope you found this tutorial helpful in learning about routing in Angular. Stay tuned for more tutorials in our "Learning Angular" series!

0 0 votes
Article Rating

Leave a Reply

35 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@Abhijit-techie
25 days ago

the tutorial is too fast and many topics gathered at once…please break it down in small tutorials

@Flo22222
25 days ago

Well done explained. Not that what I looked 100% for but very interesting! Does the routerlink in the <a> tag refresh the page and load or no?

@guilllermomolinaavila9326
25 days ago

I was stuck with the dynamic route, thanks a lot!

@nightsurvivor
25 days ago

Hi, I'm a beginner in Javascript. I'm still confused after finishing these great videos. I found another video for beginners like me in Angular and this is the link: https://www.youtube.com/watch?v=lIb_gnleUns . I've tried this part 5 and combined this part with it, and the result is awesome.
I'm sorry, I don't mean to thumb down all parts of videos. I've already thumbed up your video, sir.. These videos are the ideal starting point for learning Angular and i'm trying to do my best. Thank you for the first impression that opened my mind to learn more about Angular. My journey will be great after this ! 😁

@donmarkham9811
25 days ago

definitely not good, as why use unix commands, lol

@tejas_bajaj
25 days ago

At 9:03, in Angular 18, need to import RouterLink instead of RouterModule

@justzcross6236
25 days ago

By having a non standalone app does it change?

@teemusekki1743
25 days ago

What I'm missing here after this change <a [routerLink]="['/details', housingLocation.id]">Learn more</a> link doesn't work any more. "details" work but not this.

@kacperkepinski4990
25 days ago

mess

@user-ed8eb6cx7o
25 days ago

How create routing if you have one Component where change :id and change load data from API?

@bertholdmaier7342
25 days ago

The anchor link works only in case you set the slash in front of the details: <a routerLink="/details">Learn More</a>

@user-xx4dw3fl6t
25 days ago

You guys should update the documentation, because I am struggling with Tour of Heroes where I have to follow other instructions that do not work on my Angular version

@user-mx8po1jo9g
25 days ago

Love this guy)

@marlosbross423
25 days ago

This week, I started learning Angular and encountered some difficulty with the router. I consulted the documentation, but it wasn't until I came across a helpful video that I managed to navigate my pages successfully. However, I'm working with Angular 17 and I'm unsure if this approach is the best practice to use." tks for angular team and community.

@srdouglas1026
25 days ago

nesse caso o standalone está "false" ?

@forton615
25 days ago

The tutorial I started with did not use standalone, so this doesn't work for my application. Do I have to start over again? This is frustrating.

@nbossard
25 days ago

Also all changes are missing in details.component.ts, should be :
—————————————-
import { Component,inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute } from '@angular/router';

@Component({
selector: 'app-details',
standalone: true,
imports: [CommonModule],
template: `
<p>
details works! {{housingLocationId}}
</p>
`,
styleUrls: ['./details.component.css'],
})
export class DetailsComponent {
route: ActivatedRoute = inject(ActivatedRoute);
housingLocationId = 0;

constructor() {
this.housingLocationId = Number(this.route.snapshot.params["id"])
}
}

———————————-

@nbossard
25 days ago

FYI : in Completed code, in housing-location.component.ts, it misses the html tag `<a [routerlink]="['/details',housingLocation.id]"> Learn more</a>`

@anneyo5627
25 days ago

Great videos. The only thing what i am missing on the angular.dev site is that these video's dont match the text under it….. So I came to youtube since the (text in the) tutorial on the site is not correct and useless since its different from what the video says. The videos are great tho fortunately.

@rembautimes8808
25 days ago

I really like the content and presentation style. I tried my hand at Angular last year but gave up as I couldn’t get routing. This video gives me confidence to try it again.

35
0
Would love your thoughts, please comment.x
()
x