扩展属性指令 [英] Extending a Attribute Directive
问题描述
我想扩展内置的 routerLink
指令来创建我自己的指令,称为 customRouterLink
.
I would like to extend the built-in routerLink
directive to create my own directive called customRouterLink
.
我只是创建了一个扩展 RouterLinkWithHref
的类:
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>
导致以下错误的原因:
Can't bind to 'customRouterLink' since it isn't a known property of 'a'.
但是,如果我从指令定义中删除 extends RouterLinkWithHref
它可以工作.
However, if I remove extends RouterLinkWithHref
from the directive definition it works.
示例 plunkers:
Example plunkers:
CustomLinkDirective extends RouterLinkWithHref
- 上面显示错误立>CustomLinkDirective
未扩展RouterLinkWithHref
- 创建的指令没有错误
CustomLinkDirective extends RouterLinkWithHref
- Shows error aboveCustomLinkDirective
not extendingRouterLinkWithHref
- Directive created without error
推荐答案
我在尝试扩展 RouterLinkWithHref 类时遇到了同样的错误.错误来自您没有为指令包含 @Input 装饰器的事实.您正在尝试传入您的 url 字符串 <a [customRouterLink]="'http://www.google.com'">custom link</a>
,但 Angular 找不到属性将此值绑定到您的类中并引发错误.要解决这个问题,只需添加 @input('customRouterLink') link: string
.
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
.
这篇关于扩展属性指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!