Search code examples
angularrouterlink

RouterLink selector


from the official docs the RouterLink directive selector is :not(a):not(area)[routerLink] ( it means select all elements with routerLink attribute tha are not anchor or area elements, right?)

How is it possible then to work on an anchor tag like this:

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

Solution

  • There are 2 RouterLink directives:

    @Directive({selector: 'a[routerLink],area[routerLink]'})
    export class RouterLinkWithHref implements OnChanges, OnDestroy {
    }
    
    @Directive({selector: ':not(a):not(area)[routerLink]'})
    export class RouterLink {
    }
    

    There are some small differences between the two, which I imagine the Angular team have felt is best served by maintaining two different directives.

    But to answer your question, yes, your HTML example works. You will probably find something equivalent to this usage in 99.99% of Angular projects.

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

    The differences

    a[routerLink] has these additions:

    constructor(/*args*/) {
      this.subscription = router.events.subscribe((s: Event) => {
        if (s instanceof NavigationEnd) {
          this.updateTargetUrlAndHref();
        }
      }
    }
    
    ngOnChanges(changes: {}): any { this.updateTargetUrlAndHref(); }
    

    And some extra click handling - to override the default <a> and <area> click handling.

    Links

    Source code: https://github.com/angular/angular/blob/master/packages/router/src/directives/router_link.ts

    Docs for a[routerLink]: https://angular.io/api/router/RouterLinkWithHref

    Docs for :not(a)[routerLink]: https://angular.io/api/router/RouterLink