0

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)

Gil Epshtain
  • 8,670
  • 7
  • 63
  • 89

2 Answers2

1

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;
}
Asura
  • 859
  • 5
  • 15
  • yes, this will work, thank you. BUT this will set the active class when clicking on the link. But how to set the active class when scrolling to the section. For example, when I scroll to page2 I would like to add the active class as well – Gil Epshtain Jan 20 '18 at 22:28
  • I believe that is only possible by Retrieve the client resolution via window.innerWidth/window.innerHeight and then using mouse event such mouseenter on the page and then changing the page id when the mouse y coordinate pass a certain threshhold(y value) which depend on the client resolution. – Asura Jan 20 '18 at 22:57
  • this isn't a new idea. I was wondering if you can use `routerLinkActive` to know if the link is valid, something like `routerLinkActive='#ID'` (this is of course not valid code) – Gil Epshtain Jan 20 '18 at 23:24
  • routerLinkActive is used to add a css class to the active route or assign a template variable, example of what can be done with routerLinkActive with routerLinkActiveOptions : https://angular.io/api/router/RouterLinkActive – Asura Jan 21 '18 at 00:26
0

you can use boostrap to make your coding much more easier here is one of the function of bootstrap that your are looking for

user3121362
  • 85
  • 1
  • 12