jwa
jwa

Reputation: 3281

Extending a Attribute Directive

I would like to extend the built-in routerLink directive to create my own directive called customRouterLink.

I have simply created a class that extends RouterLinkWithHref:

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

  constructor(router: Router, route: ActivatedRoute, locationStrategy:  LocationStrategy) {
    super(router, route, locationStrategy);
  }

  @Input()
  set customRouterLink(data: any[]|string) {
      console.log("custom directive input", data);
  }

}

I am attempting to create an instance of this directive:

<a [customRouterLink]="'http://www.google.com'">custom link</a>

Which is causing the following error:

Can't bind to 'customRouterLink' since it isn't a known property of 'a'.

However, if I remove extends RouterLinkWithHref from the directive definition it works.

Example plunkers:

Upvotes: 3

Views: 2205

Answers (3)

Francis Robitaille
Francis Robitaille

Reputation: 632

I did it successfully with

@Directive({
    selector: '[customRouterLink]'
})
export class CustomRouterLinkDirective extends RouterLinkWithHref implements OnInit, OnDestroy {

    @Input('customRouterLink')
    link: string;

    constructor(
        router: Router,
        route: ActivatedRoute,
        locationStrategy: LocationStrategy
    ) {
        super(router, route, locationStrategy);
    }

    ngOnInit() {
        this.href = this.routerLink = this.link;
    }
}

Don't forget you need to register your directive into app.module.ts

This is how you can use it

 <a [customRouterLink]="/any/any">link</a>

Upvotes: 1

ev1lde4dly
ev1lde4dly

Reputation: 11

I ran into the same error when attempting to extend the RouterLinkWithHref class. The error is coming from the fact that you do not include an @Input decorator for your directive. You are attempting to pass in your url string <a [customRouterLink]="'http://www.google.com'">custom link</a>, but Angular cannot find a property to bind this value to within your class and throws an error. To resolve this simply add @input('customRouterLink') link: string.

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657721

You need to add CustomLinkDirective to declarations of your module or better create a module for CustomLinkDirective and add this module to imports: [...] of the module where you want to use your router link.

Upvotes: 0

Related Questions