Hi Thomas,

Here is a directive that takes anchors and rewrites them to use the router.

import { Directive, ElementRef, ContentChildren, ViewChildren } from 
'@angular/core';
import { Router, RouterLink  } from '@angular/router'


@Directive({ selector: '[rewriteAnchors]' })
export class rewriteAnchors {
    
    @ViewChildren(RouterLink) AnchorsInView: QueryList<RouterLink>;
    @ContentChildren( RouterLink) AnchorsInContent: QueryList<RouterLink>;
    
    
    constructor(
      private el: ElementRef,
      private router: Router
    ) { }
    
    ngAfterViewInit() {
      const el = this.el.nativeElement;
      //window.el = el;
      console.log(this.AnchorsInView, this.AnchorsInContent, el)
      if (el) {  
        // this code only gets run in the browser, as other envs have 
(akaik) no nativeelement
        const links = Array.from(el.querySelectorAll("a"))
          .filter(l => !l.hasAttribute('ng-reflect-router-link'))
          .map(l => (console.log(l),l))
          .forEach(l => l.addEventListener('click', this.reroute(this)))
          ;
      } 
    }
    
  
    reroute(me) {
      // use the closure to keep a reference to me(this)
      return function reroute(ev) {
        // might be confusing, but 'this' points to the element 
        // orignating the click.
        ev.preventDefault(); 
        const url = this.getAttribute("href")
        me.router.navigateByUrl(url);
      };
    }
}



Is that what you are looking for?

Regards
Sander

-- 
You received this message because you are subscribed to the Google Groups 
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to angular+unsubscr...@googlegroups.com.
To post to this group, send email to angular@googlegroups.com.
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply via email to