Home > Enterprise >  Can I use anchor tags to jump to different locations on different pages in Angular?
Can I use anchor tags to jump to different locations on different pages in Angular?

Time:12-15

I'm using anchor tags in my navbar to send users to different sections on the about page. Problem is, it only works if I'm already in the about page. It doesn't jump to the specific location I want it to when I click on those links in my navbar from other pages (like for example, homepage).

This is my navbar.html:

      <mat-menu #aboutMenu="matMenu">
        <button mat-menu-item>
          <a href="/about-us#about"> About </a>
        </button>
        <button mat-menu-item>
          <a href="/about-us#token"> Token </a>
        </button>
        <button mat-menu-item>
          <a href="/about-us#team"> Team </a>
        </button>
      </mat-menu>

And this is my about.html:

    <a name="about">
      <h1>About</h1>
    </a>
     .
     .
     .
    <a name="token">
      <h2>Token Details</h2>
    </a>
     .
     .
    <a name="team">Team Members</a>

CodePudding user response:

I solved using the following code:

.html:

<a [routerLink]="'/about-us'" fragment="about" (click)="onAnchorClick()"> About </a>

.ts:

  onAnchorClick ( ) {
    this.route.fragment.subscribe ( f => {
      const element = document.querySelector ( "#"   f )
      if ( element ) element.scrollIntoView ( true )
    });
  }

CodePudding user response:

To navigate to another page on clicking a button just use angular event binding syntax.The event binding listens to the click event of the button and calls its respective method in the component.ts file. Refer link for more understanding: https://angular.io/guide/event-binding

  • Related