Skip to content

RouterLink not working correctly with anchors inside SVG elements #48854

@sdarnell

Description

@sdarnell

Which @angular/* package(s) are the source of the bug?

core

Is this a regression?

No

Description

RouterLink doesn't work for keyboard navigation when the anchor is inside an SVG element.
For example:

<svg xmlns="http://www.w3.org/2000/svg" ...>
  <a xmlns="http://www.w3.org/1999/xhtml" routerLink="/home">
    <g><path...></g>
  </a>
</svg>

Clicking on the shape works, but keyboard enter etc. doesn't.

The problem is that the RouterLink directive only looks for an anchor with a capitalised tag name.
But as you will see from the test, the anchor tagName is lowercase when inside an SVG element.

https://github.com/angular/angular/blob/15.1.2/packages/router/src/directives/router_link.ts#L193

    const tagName = el.nativeElement.tagName;
    this.isAnchorElement = tagName === 'A' || tagName === 'AREA';

This fails because tagName === 'a'.

If I change the anchor to <A ...> it no longer displays correctly, so that isn't an option.

My suggestion would be to use:

    const tagName = el.nativeElement.tagName.toUpperCase();
    this.isAnchorElement = tagName === 'A' || tagName === 'AREA';

or

    const tagName = el.nativeElement.tagName;
    this.isAnchorElement = tagName === 'A' || tagName === 'a' || tagName === 'AREA';

Please provide a link to a minimal reproduction of the bug

https://stackblitz.com/edit/angular-hkjkdm?file=src/app/app.component.html

Please provide the exception or error you saw

The routerLink does not work with the keyboard, here is the output from the Stackblitz:

HeroService: fetched heroes  <--- result of pressing Enter on 'Dashboard' anchor
Key keypress Enter on tag a  <--- result of pressing Enter on SVG shape
Key keypress Space on tag a  <--- result of pressing Space on SVG shape
Key keypress Space on tag A  <--- result of pressing Space on 'Dashboard' anchor

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 15.1.0
Node: 16.13.0
Package Manager: npm 8.1.0
OS: darwin arm64

Angular: 15.1.0
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, localize, platform-browser
... platform-browser-dynamic, router, service-worker

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1501.0
@angular-devkit/build-angular   15.1.0
@angular-devkit/core            15.1.0
@angular-devkit/schematics      15.1.0
@angular/cdk                    15.0.4
@schematics/angular             15.1.0
rxjs                            7.5.7
typescript                      4.8.4

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions