我想使用片段和查询参数从组件导航到其他路径。所以这里想在查询参数之前添加片段,如下所示
http://localhost:4200/home#example?fromDate=2020-03-19&toDate=2020-03-22
我已添加查询参数,但无法在查询参数之前添加片段。我使用了 NavigationExtras 它在查询参数后添加片段。
你尝试过吗
this.router.navigate(['/home'], { fragment: 'example', queryParams: { page: 1, next: 2 } });
或者天真的方式,
this.router.navigate(['/home#example'], { queryParams: { page: 1, next: 2 } });
@Component({
...
imports: [
RouterLink
],
...
})
export class Component {
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());
}
}
<a target="_blank"
(click)="addFragmentToUrl(data.id)"
>
{{ data.text }}
</a>