angularrouterlinkrouterlinkactive

How to add css class to a active in-page-link (hashtag link) - Angular


I have an Angular, single-page-website with the next layout

<body>
  <!-- Header -->
  <div class="header">
    <a [href]="{{ '#' + page1_Id }}">Page1</a>
    <a [href]="{{ '#' + page2_Id }}">Page2</a>
    <a [href]="{{ '#' + page3_Id }}">Page3</a>
  </div>

  <!-- Page1 -->
  <div [id]="page1_Id">
    I'm Page 1
  </div>
  <!-- Page2 -->
  <div [id]="page2_Id">
    I'm Page 2
  </div>
  <!-- Page3 -->
  <div [id]="page3_Id">
    I'm Page 3
  </div> 
</body>

(where the pageN_Id is a components variables)

When I click the header's link pageN the window will scroll to pageN (using in-page-navigation, <a href="#someId">)

Now I would like to add an 'active' css-class to the a-link element when the link was clicked.

I know the directives routerLink and routerLinkActive, but how to use them with a in-page-link (and not as a simple between pages link)


Solution

  • Create a variable that is set to the page id of the href link when clicked.

    example:

     <a id="{{page1_Id}}" class="nav-link" [ngClass]="{ 'active': pageid== page1_Id  }" (click)="clicked(page1_Id )"></a>
    

    now in your .ts component file:

    clicked(object) {
        this.pageid= object;
    }