How to Navigate Fragment URL in Angular 15?
Last Updated :
14 May, 2024
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 and facilitating content sharing and navigation.
Prerequisites
What is a fragment URL?
A fragment URL, also known as a fragment identifier or hash URL, is a URL that includes a fragment identifier preceded by a hash symbol (#). The fragment identifier refers to a specific section or element within a web page. In Angular applications, fragment URLs are commonly used for implementing client-side routing and navigation to specific sections or components within a single-page application.
Navigating to Fragment URLs in Angular
Angular provides the Router
service, which allows us to navigate between different views within our application. To navigate to a fragment URL, we can use the navigate
method of the Router
service and specify the desired fragment as part of the navigation options
Step 1: Create an angular application
To create a new angular application we can use,
ng new fragment-urls
cd fragment-urls
This will create a new app in the directory fragment-urls, we then use the cd command to change the active directory.
Folder Structure
Folder StructureDependencies
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Step 2: Add fragment routes
Fragment URL just targets the element whose id is the same as that of the fragment, and scrolls to that element. We will create a nav bar with three hyperlinks and a section for each. We will provide a unique id for each of the sections and also the same in the fragment attribute for the button.
HTML
<!-- app.component.html -->
<nav>
<a routerLink="/" fragment="about-us">About Us</a>
<a routerLink="/" fragment="services">Services</a>
<a routerLink="/" fragment="contact-us">Contact Us</a>
</nav>
<section id="about-us">
<h1>
About Us
</h1>
</section>
<section id="services">
<h1>
Services
</h1>
</section>
<section id="contact-us">
<h1>
Contact Us
</h1>
</section>
CSS
/* app.component.scss */
nav {
width: 100vw;
height: 56px;
position: sticky;
top: 0;
display: flex;
gap: 16px;
justify-content: center;
align-items: center;
background-color: aquamarine;
color: green;
font-size: 20px;
a {
text-decoration: none;
color: inherit;
cursor: pointer;
&:hover {
color: red;
text-decoration: underline;
}
}
}
section {
width: 100vw;
height: 200px;
padding: 16px;
border: 1px solid black;
&:nth-of-type(odd) {
background-color: lightgray;
}
}
JavaScript
// app.component.ts
import { ViewportScroller } from '@angular/common';
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, RouterLink],
templateUrl: './app.component.html',
styleUrl: './app.component.scss',
})
export class AppComponent {
title = 'fragment-urls';
constructor(viewport: ViewportScroller) {
viewport.setOffset([0, 56]);
}
}
JavaScript
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withInMemoryScrolling } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes, withInMemoryScrolling({
anchorScrolling: 'enabled',
scrollPositionRestoration: 'enabled',
}))]
};
To start the application run the following command
ng serve --open
Output
How to Navigate Fragment URL in Angular 15?
Similar Reads
How to Add Special Characters in URL in Angular?
When developing web applications with Angular, you might encounter situations where you need to include special characters in URLs. Special characters such as spaces, ampersands, question marks, and others often need to be encoded correctly to ensure the URL is valid and functions as expected. In th
4 min read
How to Get All Route Params/Data in Angular?
In Angular, managing route parameters and extracting data from routes is important for creating dynamic and responsive web applications. Route parameters allow you to pass information in URLs, and accessing this data enables your application to make decisions and render content dynamically. This art
4 min read
Angular 17 router.navigate
The router.navigate method in Angular 17 is used to navigate to a specific route programmatically. It allows you to change the browser URL and load the corresponding component without the need for a traditional link or reload. This is particularly useful when you want to navigate based on user inter
2 min read
How do you navigate programmatically in Angular?
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 c
3 min read
How to detect a route change in AngularJS ?
In this article, we will see how to detect a route change in AngularJS. In order to detect route change at any moment in AngularJS, this can be achieved by using the $on() method. The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/vi
2 min read
How to Enable HTML 5 Mode in Angular 1.x ?
HTML5 mode in Angular1.x is the configuration that replaces the default hash-based URLs and provides more user-friendly URLs using the HTML5 History API. This feature mainly enhances our one-page application and also provides a better experience to the users. We need to configure our server with pro
6 min read
How to create a new component in Angular?
A component in Angular is the building block for making web pages. It is a reusable block of code that can be used anywhere in the app any number of times. It provides scalability, reusability, and readability. Each component does a specific job like showing a menu, a photo or a card, etc. In this a
3 min read
How To Get The URL Parameters Using AngularJS?
In AngularJS, retrieving URL parameters is essential for managing dynamic content and user interactions based on the URL state. In this article, we'll learn various approaches to achieve this.Table of ContentApproach 1: Using ActivatedRoute ServiceApproach 2: Using Router ServiceApproach 3: Using UR
3 min read
How to execute a routing in the AngularJS framework ?
In this article, we will learn about how we can perform routing in AngularJS, along with understanding its implementation through the code example. Â Routing in AngularJS helps to develop Single Page Applications, which is a web app that loads only a single page, and the part of the page instead of t
6 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