6

How can I extend the [routerLink] directive from the Angular Router v3 so I can wrap some custom functionality myself? I've taken a look at the RouterLinkWithHref directive and it appears that is what I want to extend, so I produced this:

ExtendedRouterLinkDirective

import {Directive, Input} from '@angular/core';
import {RouterLinkWithHref} from "@angular/router";
import {Model} from "../Classes/Model.class";

@Directive({
    selector: 'a[extendedRouterLink]'
})
export class ExtendedRouterLinkDirective extends RouterLinkWithHref {
    @Input('extendedRouterLink') model : Model;

    // Future custom logic
}

And I try and use it like so:

<a [extendedRouterLink]="model">

And I include it in the directives array of my component:

...
directives: [ROUTER_DIRECTIVES, ExtendedRouterLinkDirective],
...

Yet, I get the following runtime error:

"Template parse errors: Can't bind to 'extendedRouterLink' since it isn't a known native property"

If I remove the extends RouterLinkWithHref from my directive, it works without errors. What am I doing wrong?

marked-down
  • 9,958
  • 22
  • 87
  • 150

1 Answers1

2

I need the same. Using your post, I was able to make it work. Here is what was missing:

@Input() mgiRouterLink: string ngOnInit() 

ngOnInit() {
    this.href = this.routerLink = this.mgiRouterLink  
}

The parent routeLink directive is expecting this.href and this.routerLink to hold the data from the DOM attribute. Now it look like this:

import {Directive, Input} from '@angular/core';
import {RouterLinkWithHref} from "@angular/router";
import {Model} from "../Classes/Model.class";

@Directive({
    selector: 'a[extendedRouterLink]' 
}) 
export class ExtendedRouterLinkDirective extends RouterLinkWithHref {

    @Input() mgiRouterLink: string ngOnInit() 

    ngOnInit() {
        this.href = this.routerLink = this.mgiRouterLink  
    } 
}
  • 2
    routerLinkActive is not working anymore, do you have a clue? – Francis Robitaille Jul 28 '20 at 17:39
  • @FrancisRobitaille I had same problem. Angular v8 implements RouterLinkActive such way, that it expects RouterLink or RouterLinkWithHref . I guess you could extend RouterLinkActive as well so it would accept your directive. – Cute pumpkin Sep 23 '21 at 12:48