2017-11-24 8 views
0

新しいディレクティブを作成する前に、この<input #inputBox (click)="getElement(inputBox)" element-directive/>を持ってinputBox要素を取得しました。@HostListenerはHTML要素を返すことができますか?

は今、私は指示にすべてを移動していると私は/リターンHTML要素へのアクセスを@HostListenerできます

input.directive.ts

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

に私はinputBox要素を取得することができますどのように貼り付けられています?

+1

が重複する可能性のために@HostLinstenerを使用する必要があります[あなたはAngular 2属性ディレクティブの中から要素HTMLにどのようにアクセスしますか?](https://stackoverflow.com/questions/38002640/how-do-you-access-the-element-html-from-within-an-angular -2属性指示文) – zgue

+0

あなたはca $ event.targetを試してみる – yurzui

答えて

0

あなたはネイティブのHTML要素にアクセスするには、ディレクティブのコンストラクタでElementRefを注入することができますhere

を見てください。

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

あなたがいけないの

関連する問題