Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Routing with Hashtag to page anchor

I wish to add some links on my Angular2 page, that when click, will jump to specific positions within that page, like what normal hashtags do. So the links would be something like

/users/123#userInfo /users/123#userPhoto /users/123#userLikes 

etc.

I don't think I need HashLocationStrategy, as I'm fine with the normal Angular2 way, but if I add directly, the link would actually jump to the root, not somewhere on the same page. Any direction is appreciated, thanks.

like image 236
Stone Avatar asked Mar 19 '16 12:03

Stone


People also ask

How do you make router use anchor tag in angular?

Make sure to import Router, ActivatedRoute and NavigationEnd at the beginning of your component and it should be all good to go. Works for me! In case you want to navigate within the same page you're already on, use [routerLink]="['. ']"

What is difference between routerLink and href?

Href is the basic attribute provided by Html to navigate through pages which reloads the page on click. routerLink is the attribute provided by angular to navigate to different components without reloading the page.

Which of the following angular tags is used to link to the route page?

To specify a relative route, use the NavigationExtras relativeTo property. In the component class, import NavigationExtras from the @angular/router . Then use relativeTo in your navigation method.

Can we give routerLink to div?

Yes it can be attached to div tag, your route is probably wrong try add / in front of route.


1 Answers

Update

This is now supported

<a [routerLink]="['somepath']" fragment="Test">Jump to 'Test' anchor </a> 
this._router.navigate( ['/somepath', id ], {fragment: 'test'}); 

Add Below code to your component to scroll

  import {ActivatedRoute} from '@angular/router'; // <-- do not forget to import    private fragment: string;    constructor(private route: ActivatedRoute) { }    ngOnInit() {     this.route.fragment.subscribe(fragment => { this.fragment = fragment; });   }    ngAfterViewInit(): void {     try {       document.querySelector('#' + this.fragment).scrollIntoView();     } catch (e) { }   } 

Original

This is a known issue and tracked at https://github.com/angular/angular/issues/6595

like image 97
Günter Zöchbauer Avatar answered Sep 19 '22 00:09

Günter Zöchbauer