0
0
Angularframework~5 mins

Query parameters and fragments in Angular

Choose your learning style9 modes available
Introduction

Query parameters and fragments help you send extra information in URLs. They let your app show different content or jump to parts of a page.

You want to filter a list on a page without changing the main URL path.
You want to remember user choices like sorting or search terms in the URL.
You want to link to a specific section inside a page using a fragment.
You want to share a URL that opens a page with special settings or views.
You want to read extra info from the URL to change what the page shows.
Syntax
Angular
this.router.navigate(['/path'], { queryParams: { key: 'value' }, fragment: 'section' });

queryParams is an object with key-value pairs for the URL query string.

fragment is a string that points to a part of the page after the # symbol.

Examples
This navigates to /products?category=books&sort=price
Angular
this.router.navigate(['/products'], { queryParams: { category: 'books', sort: 'price' } });
This navigates to /profile#settings, jumping to the settings section.
Angular
this.router.navigate(['/profile'], { fragment: 'settings' });
This navigates to /search?q=angular#results, showing search results and jumping to them.
Angular
this.router.navigate(['/search'], { queryParams: { q: 'angular' }, fragment: 'results' });
Sample Program

This component shows how to navigate with query parameters and fragments. When you click the button, it goes to /products?category=books#top. It also listens to the URL and shows the current category and fragment on the page.

Angular
import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-query-example',
  template: `
    <h2>Query Params and Fragment Example</h2>
    <button (click)="goToPage()">Go to Products with Filters</button>
    <p>Current category: {{ category }}</p>
    <p>Current fragment: {{ fragment }}</p>
  `
})
export class QueryExampleComponent {
  category = '';
  fragment = '';

  constructor(private router: Router, private route: ActivatedRoute) {
    this.route.queryParams.subscribe(params => {
      this.category = params['category'] || 'none';
    });
    this.route.fragment.subscribe(frag => {
      this.fragment = frag || 'none';
    });
  }

  goToPage() {
    this.router.navigate(['/products'], { queryParams: { category: 'books' }, fragment: 'top' });
  }
}
OutputSuccess
Important Notes

Query parameters and fragments do not reload the whole page but update the URL and app state.

Use ActivatedRoute to read query parameters and fragments inside your components.

Fragments usually scroll the page to the matching element with the same id.

Summary

Query parameters add extra info after ? in URLs to filter or customize views.

Fragments add a # part to jump to sections inside a page.

Angular's router lets you set and read these easily with navigate and ActivatedRoute.