Working with fragment in a route

In Angular, a fragment in a route is a portion of the URL that comes after the '#' symbol. Fragments are commonly used to navigate to specific sections or anchors within a page. They allow users to jump directly to a particular part of the page without reloading the entire page. Angular provides support for fragments in routes through the fragment property in the NavigationExtras object when navigating programmatically.

A fragment in a route is a link which jumps to a section or a content in the HTML page, which contains the ID mentioned in the fragment. A fragment comes after a # sign.

localhost:4200/Home#Element1

Here, Element1 is an fragment.

#1 Navigating with a Fragment

You can specify a fragment when navigating to a route using the navigate() method of the Router service.

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

constructor(private router: Router) { }

navigateToSection(): void {
  this.router.navigate(['/home'], { fragment: 'section1' });
}

In this example, '/home' is the route path, and 'section1' is the fragment. When the user navigates to the '/home' route using navigateToSection(), the browser will scroll to the element with the id 'section1' on the page.

#2 Accessing Fragment in a Component

You can access the fragment value in a component using the ActivatedRoute service.

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

constructor(private route: ActivatedRoute) { }

ngOnInit(): void {
  this.route.fragment.subscribe(fragment => {
    console.log('Fragment:', fragment);
    // Perform actions based on the fragment
  });
}

In this example, fragment is an observable that emits the fragment value whenever the fragment changes. You can subscribe to this observable in the component's ngOnInit() lifecycle hook to react to changes in the fragment.

#3 Using Fragment in Templates

You can also access the fragment directly in your component's template using the async pope with the fragment observable.

<p *ngIf="(route.fragment | async) === 'section1'">This is section 1</p>

In this example, the paragraph will be displayed if the fragment is 'section1'.

#4 Fragment Using RouterLink

To include a fragment in a routerLink,

<a [routerLink]="'/details/' + productId" fragment="description">View Details</a>

In this case, the fragment attribute specifies the fragment identifier directly.