`anchorScrolling: 'enabled'` does not work when using `ViewEncapsulation.ShadowDom`

🐞 bug report

Affected Packages

  • @angular/common - BrowserViewportScroller
  • @angular/router

Is this a regression?

No

Description

Anchor scrolling does not work when Shadow DOM is enabled: navigating via a fragment link does not cause the target element to be scrolled into view, nor is focus placed on the target element.

I believe this is caused by the way BrowserViewportScroller is currently implemented, as it queries for the target element using the document object -- with Shadow DOM enabled, the target element is not part of the document tree and thus can't be located.

🔬 Minimal Reproduction

https://stackblitz.com/edit/angular-d9gjhr

  1. In AppComponent, comment out line 8:
    -  encapsulation: ViewEncapsulation.ShadowDom
    +  // encapsulation: ViewEncapsulation.ShadowDom
  2. Click "Jump to copyright link".
    • ✅ You are scrolled to the bottom of the page, with the copyright link in view.
    • ✅ Focus moves to the copyright link (this can be verified by hitting Tab once; focus moves to the "About" link which immediately follows the copyright element).
  3. Re-enable ShadowDom (restore line 8).
  4. Click "Jump to copyright link" again.
    • ❌ Scroll position remains the same; the copyright link remains out of view.
    • ❌ Focus does not change to the copyright element.

🌍 Your Environment

See StackBlitz