问题
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 extendingRouterLinkWithHref
- Directive created without error
回答1:
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
.
回答2:
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.
来源:https://stackoverflow.com/questions/39140818/extending-a-attribute-directive