0

I want to use css anchor in my html page. And below is my code:

<a href="#test"></a>

<div id="test" name="test">123</div>

But I will get this issue. angular router issue

Actually, I don't want angular router works.

Emon
  • 1,401
  • 14
  • 24

1 Answers1

0

Docs reference: Angular Routing Navigation

A work around for this could be

Option 1: Using fragments

In your HTML file

<a [routerLink]="['/']" fragment="test"></a>

In your Typescript file

 ngOnInit() {
     this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
    }

    ngAfterViewChecked(): void {
      try {
          if(this.fragment) {
              document.querySelector('#' + this.fragment).scrollIntoView();
          }
      } catch (e) { }
    }

Option 2 : Just create method and scroll

In your HTML file

<button (click)="scroll(test)"></button>
<div #test >Your target</div>

In your .ts file

scroll(el) {
    el.scrollIntoView({ behavior: "smooth"});
}

Angular 6.1 and above also has an option called anchorScrolling but as far as I'm aware, it's still in beta

Reference to how to use anchorScrolling

Richard Pariath
  • 150
  • 2
  • 13
  • Thank you @Richard Pariath, Option 2 solve my problem. But I am not sure about option1. what `this.route` means? I have tried angular Route and Router. but still the error "fragment doesn't exist" – Emon Oct 23 '18 at 05:35