3

I'm using Angular Router and I'm trying to link to a sub-component in another route by id. Basically what would usually be done using the <a href="www.url.com/profile/#profile-header-id">.

I'm not sure if there's a built-in way for the Angular router to do this, but if not perhaps I can manually trigger the link at a later point when I know the element has been rendered.

The issue isn't linking to another route which of course is done with the Link from the Angular router. The issue is linking to an element which is found in the rendered HTML of the linked component.

Less Abstract Code Example:

So let's say my router in the app.module.ts file is

`const routes = [
  { path: '', component: HomeComponent},  
  { path: '#section3', component: HomeSection3Component}, 
  { path: 'B', component: BComponent}, 
];`

Now in component OtherComponent, I want a Link that not only takes me to the home page route ' ', but also scrolls to the element of id #section3, thereby skipping all the irrelevant stuff.

My home component has nested components for each one of the sections of the page. Each section/component has an id.

home.component.html

`<main>
     <app-section1></app-section1>
     <app-section2></app-section2>
     <app-section3></app-section3>
</main>`

However, all I can see is a blank page when clicking the button <button routerLink="#section3">Go to homepage section 3</button> on the B page.

Mauricio Gonzalez
  • 127
  • 2
  • 3
  • 11

2 Answers2

5

The most elegant solution is just to add a fragment property to add the #section3 to the URL and then make it jump to this section with an anchor tag.

<div [routerLink]="['']" fragment="section3"> <a href="#section3">Jump to 'Section3' anchor </a> </div>

Mauricio Gonzalez
  • 127
  • 2
  • 3
  • 11
3

Use the routerLink directive combined with its fragment input property.

<a routerLink fragment="section3">Section 3</a>

With your routes, the rendered DOM is

<a href="/#section3">Section 3</a>

Make sure that you have imported RouterModule in the declaring module of the component in which you use the routerLink directive. Example:

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

@NgModule({
  declarations: [
    HomeComponent,
    HomeSection1Component
    HomeSection2Component,
    HomeSection3Component,
  ],
  imports: [
    CommonModule,
    RouterModule,
  ],
})
export class HomeModule {}
Lars Gyrup Brink Nielsen
  • 3,939
  • 2
  • 34
  • 35