Reputation: 3281
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:
CustomLinkDirective extends RouterLinkWithHref
- Shows error aboveCustomLinkDirective
not extending RouterLinkWithHref
- Directive created without errorUpvotes: 3
Views: 2205
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
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
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