How do you navigate programmatically in Angular?
Last Updated :
16 Apr, 2024
Angular is a popular framework for building dynamic web applications, and one of its important features is its routing system. In Angular, we use a Router module, which allows us to navigate between different components easily. While navigation often occurs as a result of certain user actions like clicking on a link, there are also several use cases where we need to navigate programmatically. In this article, we'll look at the way to navigate programmatically in Angular.
Steps to Set Up Angular Application
Step 1: Create an Angular application using the following command.
ng new my-app
Step 2: After creating the project, navigate to the project folder using the below command.
cd my-app
Example 1: Programmatic Navigation Triggered by User Interaction
In this example, we'll see how we can navigate from one component to another programmatically by handling user click.
Step 1: Generate a target component and a source component for navigation purpose using the below commands.
ng generate component target
ng generate component source
Folder Structure:
project structureCode Example:
HTML
<!-- target.component.html -->
<h1>This is the target component!</h1>
HTML
<!-- source.component.html -->
<h1>I'm the source component</h1>
<button (click)="onButtonClick()">Go to Target Route</button>
HTML
<!-- app.component.html -->
<router-outlet></router-outlet>
JavaScript
//app.routes.ts
import { Routes } from '@angular/router';
import { TargetComponent } from './target/target.component';
import { AppComponent } from './app.component';
import { SourceComponent } from './source/source.component';
export const routes: Routes = [
{ path: '', component: SourceComponent },
{ path: 'target', component: TargetComponent },
];
JavaScript
//source.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-source',
standalone: true,
imports: [],
templateUrl: './source.component.html',
styleUrl: './source.component.css',
})
export class SourceComponent {
constructor(private router: Router) { }
onButtonClick() {
this.router.navigate(['/target']);
}
}
Step 2: Apply the changes and run the application by running the following command.
ng serve
Output:
output for example 1Example 2: Programmatic Navigation with Route Parameters
In this example, we'll navigate programmatically to another route with a route parameter when a button is clicked. It is beneficial whenever we need to pass a data along with the route.
Step 1: Update the Source Component HTML template by writing template code in source.component.html. Here we'll pass the data to the handler function.
HTML
<!-- source.component.html -->
<h1>I'm the source component</h1>
<button (click)="onClick('user1')">Visit Target Page</button>
HTML
<!-- target.component.html -->
<h1>Hello {{username}}</h1>
<h3>This is the target component</h3>
JavaScript
//target.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-target',
standalone: true,
imports: [],
templateUrl: './target.component.html',
styleUrl: './target.component.css',
})
export class TargetComponent implements OnInit {
username: string = '';
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe((params) => {
this.username = params['username'];
});
}
}
JavaScript
//source.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-source',
standalone: true,
imports: [],
templateUrl: './source.component.html',
styleUrl: './source.component.css',
})
export class SourceComponent {
constructor(private router: Router) { }
onClick(user1: string) {
this.router.navigate(['/target', user1]);
}
}
JavaScript
//app.routes.ts
import { Routes } from '@angular/router';
import { TargetComponent } from './target/target.component';
import { AppComponent } from './app.component';
import { SourceComponent } from './source/source.component';
export const routes: Routes = [
{ path: '', component: SourceComponent },
{ path: 'target/:username', component: TargetComponent },
];
Step 2: Apply the changes and run the application using the following command.
ng serve
Output:
output for example 2
Similar Reads
How to programmatically navigate using React Router ? React Router provides a way to navigate between different parts of an application when certain events occur, such as button clicks or form submissions. Programmatically navigating allows us to change the URL of an application without a full page reload, enabling a smoother user experience. We will d
3 min read
How to Navigate Fragment URL in Angular 15? Fragment navigation is important in Angular applications for creating deep linking and bookmarking functionality within a single-page application (SPA). It allows users to navigate directly to specific sections or components within a page without reloading the entire page, enhancing user experience
3 min read
Angular PrimeNG TabView Programmatic Control Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see how to use the TabView Programmatic Control in Angular PrimeNG. The Tab
3 min read
How To Prevent Scrolling With Navigation in Angular Component? When navigating between routes in an Angular application, the browser's scroll position is often reset to the top of the page. This can be frustrating for users who want to maintain their scroll position between route changes. In this article, we'll explore how to prevent scrolling with navigation i
10 min read
Angular PrimeNG TabView Programmatic Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the TabView Programmatic in Angular PrimeNG. We will also l
3 min read
How do you configure routes in Angular? In Angular, configuring routes is an important part of building single-page applications (SPAs) and managing navigation between different components. By defining routes, we can map URLs to specific components, enabling users to access different views within our application. This enhances user experi
5 min read