In jQuery we can handle click on element without write anything in view:
$("#tableId thead tr th").on("click", function() {
console.log('click on TH');
});
Is it possible do something the same in Angular 4?
You can achieve it by HostListner (MouseDown) Event, where when your mouse down event is fired it calls listner event where you have to find taget element as below:
You can get required element by Class, ID, Tag as per your requirement
i.e. (event.target.className=="xyz")
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
}
}
You can try this
HTML
<table>
<thead>
<tr>
<th id="elementId"></th>
</tr>
</thead>
<table>
TS
@HostListener('click', ['$event'])
onClick(event) {
if (event.target.id === 'elementId')
console.log('Click...')
}
But this will listen to all the click event in the html we have to check based on the element id
Try like this this:
<button (click)="myEvent($event)">My Button</button>
export class AppComponent {
myEvent(event) {
console.log(event);
}
}
Viewthis is how you invoke click function in Angular 2/4
<button (click)="clickMe()">Hit me</button>
View
(click)="..."to an element and generate such elements using*ngFor="..."to get the click handler added everywhere.