2017-08-03 5 views
1

角度4のhtml要素をjQueryのようにクリックしますか?私たちはビューには何も書くことなく、要素をクリックして処理することができますjQueryので

$("#tableId thead tr th").on("click", function() { 
    console.log('click on TH'); 
}); 

は、それが角度4で同じものを可能なんですか?

+0

いいえ要素に '(click)=" ... "を追加し、' * ngFor = "を使用して要素を生成できます。クリックハンドラをどこにでも追加することができます。 –

+0

あなたはあなたのコンポーネントでaosiを使用することができます。それは非常にいいです..しかしあなたはそれを行うことができます –

答えて

2

あなたはHostListner(MouseDownイベント)イベント、あなたのマウスでそれを達成することが可能でクリック機能を呼び出す方法ですあなたが以下のようなtaget要素を見つけなければならないlistnerイベントを呼び出します:

あなたのrequiに応じてクラス、ID、タグで必要な要素を取得できますリーメント

すなわち(event.target.className == "XYZ")あなたはこの

HTMLを試すことができます

import { Component, ElementRef} from "@angular/core"; 

constructor(private el: ElementRef) { 
} 

ngAfterViewInit() 
{ 
    this.RegisterMouseDown();  
} 

RegisterMouseDown() { 
    this.el.nativeElement.removeEventListener("mousedown", this.OnMouseDown.bind(this)); 
    this.el.nativeElement.addEventListener("mousedown", this.OnMouseDown.bind(this)); 
} 

OnMouseDown(event:any) { 
    if (event.target != null && event.target=="th") { 
     //user has clicked on th 
    } 
    else if (event.target != null && event.target=="img") { 
     //user has clicked on img 
    } 
} 
0

この本のように試してみてください:

<button (click)="myEvent($event)">My Button</button> 

export class AppComponent { 

    myEvent(event) { 
    console.log(event); 
    } 

} 
+0

私はそれを知っていました、 'View'で何も書いてはいけません –

0

これはあなたが角度の2/4

<button (click)="clickMe()">Hit me</button> 
+0

私はそれを知っていました、ビュー ' –

1

<table> 
     <thead> 
     <tr> 
     <th id="elementId"></th> 
     </tr> 
     </thead> 
    <table> 

TS

@HostListener('click', ['$event']) 
    onClick(event) { 
    if (event.target.id === 'elementId') 
     console.log('Click...') 

    } 

しかし、これは聞くだろう要素idに基づいてチェックする必要があるhtmlのすべてのclickイベント

関連する問題