Extending a Attribute Directive

久未见 提交于 2019-12-10 18:48:00

问题


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 above
  • CustomLinkDirective not extending RouterLinkWithHref - 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!