1

I looked at this question: How to set Bootstrap navbar “active” class in Angular 2? which shows how to link to a separate page. However, in my case I would like to link using an anchor to a section on the same page.

In the code mentioned below it's not escaping the string interpolation.

<ul class="nav navbar-nav">
  <li [routerLinkActive]="['active']"> <a [routerLink]="['#'+sectionName]">One</a></li>
  ...
</ul>

Its rendering as href="/%23Home" instead of href="#Home"

Rahul Dagli
  • 4,301
  • 15
  • 47
  • 85

2 Answers2

1

use 'fragment="sectionName"' in your link:

<a [routerLink]="['/']" fragment="education">
  link to user component
</a>

output: /#education

More information: https://angular.io/api/router/RouterLink

0

Just bind the value to the href attribute instead of using a routerLink directive.

<a [href]="'#'+sectionName">One</a>

Or you could build your own directive:

@Directive({
  selector: 'a[anchorLink]'
})
export class AnchorLinkDirective {
  @Input()
  @HostBinding('attr.href')
  public get anchorLink() {
    return '#' + this.link;
  }

  public set anchorLink(value: string) {
    this.link = value;
  }

  @Input()
  public anchorLinkActive: string;

  private link: string;
  private ngUnsubscribe$ = new Subject();

  constructor(private router: Router, private renderer: Renderer2, private element: ElementRef) {
    this.router.events.takeUntil(this.ngUnsubscribe$).subscribe(e => {
      if(e instanceof NavigationEnd) {
        let parts = e.urlAfterRedirects.split('#');
        let element = this.element.nativeElement as HTMLElement;
        if(this.anchorLinkActive && parts[parts.length - 1] === this.link) {
          this.renderer.addClass(element, this.anchorLinkActive);
        } else if(element.classList.contains(this.anchorLinkActive)) {
          this.renderer.removeClass(element, this.anchorLinkActive);
        }
      }
    });
  }

  ngOnDestroy() {
    this.ngUnsubscribe$.next();
    this.ngUnsubscribe$.complete();
  }
}

Note: This directive is pretty basic and doesn't cover a change of the anchorLinkActive input.

cyr_x
  • 13,987
  • 2
  • 32
  • 46
  • Actually I also want to set the class as active when user clicks and navigates to the particular section that's why I tried using `routerLink`. – Rahul Dagli Aug 01 '17 at 14:13