Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular – routerLink – Focus

I’m having trouble with focus on routerLink.

The first line shows the perfect URL with the theoretical focus but doesn’t focus on anything.
The second line focus well but reloads the complete page.
What can I do to use routerLink and focus on a specific input?

Origin: Component1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<a [routerLink]="'first'" fragment="name"> first </a>


<a href="{{ '/first#name' }}"> first </a>

Target: component2

<input
#name
id="name"
matInput
(ngModelChange)="change()"/>

>Solution :

Enable anchorScrolling in your app-routing module.

const routes: Routes = [{ ... }];

@NgModule({
  imports: [RouterModule.forRoot(routes, { anchorScrolling: 'enabled' })],
  exports: [RouterModule],
})
export class AppRoutingModule {}

I don’t know why this is disabled by default.

If the link is clickable more than once you will have to set onSameUrlNavigation to 'reload' as well.

const routes: Routes = [{ ... }];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      anchorScrolling: 'enabled',
      onSameUrlNavigation: 'reload',
    }),
  ],
  exports: [RouterModule],
})
export class AppRoutingModule {}

See all of the options here: https://angular.io/api/router/ExtraOptions

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading