【问题标题】:Extending a Attribute Directive扩展属性指令
【发布时间】:2016-08-25 08:56:16
【问题描述】:

我想扩展内置的routerLink 指令来创建我自己的指令customRouterLink

我只是创建了一个扩展 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);
  }

}

我正在尝试创建此指令的实例:

<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,它会起作用。

示例 plunker:

【问题讨论】:

  • 你最后解决了吗?正在考虑做类似的事情

标签: angular angular2-directives


【解决方案1】:

我在尝试扩展 RouterLinkWithHref 类时遇到了同样的错误。该错误来自您没有为指令包含 @Input 装饰器这一事实。您正在尝试传入您的 url 字符串 &lt;a [customRouterLink]="'http://www.google.com'"&gt;custom link&lt;/a&gt;,但 Angular 找不到将这个值绑定到您的类中的属性并引发错误。要解决此问题,只需添加 @input('customRouterLink') link: string

【讨论】:

    【解决方案2】:

    您需要将CustomLinkDirective 添加到您的模块的declarations,或者更好地为CustomLinkDirective 创建一个模块并将此模块添加到您要使用路由器链接的模块的imports: [...]

    【讨论】:

    • 我创建了一个新的插件,在模块的declarations 中包含CustomLinkDirective,它仍然无法正常工作。想法? plnkr.co/edit/8JMdOQ4S1COHOkgA39kT
    • 另外,请注意,如果不是extend RouterLinkWithHref ,该指令可以正常工作。目前尚不清楚是否/为什么缺少declarations 会对此产生影响。
    • 其实我也不知道。但是我想知道为什么它在没有添加到declarations 或者你是否将它添加到组件的directives: [] 时会起作用?
    • 是的,它是组件的directives的一部分
    • 扩展RouterLinkWithHref是否成功?
    【解决方案3】:

    我成功了

    @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;
        }
    }
    

    别忘了你需要将你的指令注册到 app.module.ts

    你可以这样使用它

     <a [customRouterLink]="/any/any">link</a>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多