【问题标题】:Access to attribute in directive访问指令中的属性
【发布时间】:2019-06-08 18:22:29
【问题描述】:

我一直在尝试从指令绑定中访问 href 值,但没有任何运气。

<a class="u-link-default" [attr.href]="tosUrl">Terms</a>

指令

@Directive({
  selector: 'a'
})
export class ExternalLinkDirective implements OnInit, OnChanges {
  @Input() href: string;
  @HostBinding('rel') rel: string;
  @HostBinding('target') target: string;

  constructor() {}

  ngOnInit() {
    console.log(this.href); // no value
  }

  ngOnChanges() {
    console.log(this.href); // no value
  }
}

PD:&lt;a class="u-link-default" href="https://fakedomain.com"&gt;Terms&lt;/a&gt; 有效,我已经检查过“tosUrl”不为空。

【问题讨论】:

    标签: angular binding angular2-directives


    【解决方案1】:

    [attr.href]="tosUrl" 更改为[href]="tosUrl"

    【讨论】:

    • 我这样做了 条款 因为我不想松开属性绑定。我知道它不是那么优雅,但它可以工作,我想知道是否有可能访问 de attr。以更好的方式指示。
    • 是的,您可以访问指令中的属性。您可以访问本机元素,只需将其注入构造函数中:constructor(private element: ElementRef){}
    猜你喜欢
    • 2017-06-18
    • 2012-08-08
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多