扩展属性指令 [英] Extending a Attribute Directive

查看:75
本文介绍了扩展属性指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想扩展内置的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>

这是导致以下错误的原因:

Which is causing the following error:

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.

插栓示例:

  • CustomLinkDirective extends RouterLinkWithHref - Shows error above
  • CustomLinkDirective not extending RouterLinkWithHref - 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆