@HostListener可以返回HTML元素吗?

时间:2017-11-24 08:06:41

标签: html angular

在创建新指令之前,我使用<input #inputBox (click)="getElement(inputBox )" element-directive/>来获取inputBox元素。

现在我已将所有内容都移到了指令中,我仍然坚持如何将inputBox元素转换为

input.directive.ts

@Directive({
    selector: '[element-directive]'
})
@HostListener('click', ['$event'])
public onClick($event) {
    console.dir($event); // mouse click event, not html element
}

@HostListener可以访问/返回HTML元素吗?

1 个答案:

答案 0 :(得分:0)

你应该看here

您可以在指令构造函数中注入ElementRef以访问本机HTML元素:

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[element-directive]'
})
export class HighlightDirective {
    private myDomEl;
    constructor(el: ElementRef) {
       this.myDomEl = el.nativeElement;         // <= native HTML INPUT element in your example, then use in on click event
    }
}

你不需要使用@HostLinstener