Vijay
Vijay

Reputation: 431

How to add fragment before query params in angular 8

I want to navigate from component to other route with fragment and query parameters. So here want to add fragement before query params like as below

http://localhost:4200/home#example?fromDate=2020-03-19&toDate=2020-03-22

I have added query params but unable to add fragment before query parameters. I used NavigationExtras it's addding fragment after query params.

Upvotes: 3

Views: 1343

Answers (3)

Yurii Hierts
Yurii Hierts

Reputation: 1920

Component

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

@Component({
  imports: [
    RouterLink
  ],
})
export class Component {
  @Input() id!: string;
  constructor(private route: ActivatedRoute) {}

  getQueryParams() {
    return this.route.snapshot.queryParams;
  }
}

Template

<a routerLink="."
   [fragment]="id"
   [queryParams]="getQueryParams()"
>
  Url text
</a>

Upvotes: 0

Yurii Hierts
Yurii Hierts

Reputation: 1920

Component

@Component({
  ...
  imports: [
    RouterLink
  ],
  ...
})
export class Component {
  @Input() id!: string;

  constructor(
    private location: Location,
    private router: Router,
    private route: ActivatedRoute
  ) {}

  addFragmentToUrl(fragment: string): void {
    const currentUrlTree = this.router.createUrlTree(
      this.route.snapshot.url.map(u => u.path),
      {
        fragment,
        queryParams: this.route.snapshot.queryParams,
        queryParamsHandling: 'merge',
      }
    );

    this.location.go(currentUrlTree.toString());
  }
}

Template

<a target="_blank"
   (click)="addFragmentToUrl(id)"
>
  Url text
</a>

Upvotes: 0

Ismail
Ismail

Reputation: 1316

Have you tried,

this.router.navigate(['/home'], { fragment: 'example', queryParams: { page: 1, next: 2 } });

or naive way,

this.router.navigate(['/home#example'], { queryParams: { page: 1, next: 2 } });

Upvotes: 1

Related Questions