代码中html元素的访问指令

时间:2018-10-19 13:34:12

标签: angular

是否可以通过代码从HTMLElement检索自定义@directive?

例如假设我已经声明了以下指令

@Directive({selector: '[appCustomDirective]'}) export class MyCustomDirective { public MyVariable: string; }

附在按钮上的

<button appCustomDirective>My button<button>

如果我将按钮作为HTMLElement变量,是否可以:

  • 检查是否附加了appCustomDirective?
  • 获取指令实例?

1 个答案:

答案 0 :(得分:2)

您应该能够通过返回的元素上的注入器访问指令。

组件:

usermanager

指令:

@Component({
  selector: 'app-my-custom-component',
  template: `
    <button id="with-directive" appMyCustomDirective>Click Me</button>
    <button id="without-directive">Click Me Too</button>
  `
})
export class MyCustomComponent {
}

测试:

@Directive({
  selector: '[appMyCustomDirective]'
})
export class MyCustomDirective {
  public myVariable = 'hello there!';
}