1

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?

2
  • No. You can add (click)="..." to an element and generate such elements using *ngFor="..." to get the click handler added everywhere. Commented Aug 3, 2017 at 11:20
  • you can aosi use jquery in your component .. it's not very nice .. but you can do it Commented Aug 3, 2017 at 11:21

4 Answers 4

1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

Try like this this:

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

export class AppComponent {

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

}

1 Comment

I knew it, I want to not write anything in View
0

this is how you invoke click function in Angular 2/4

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

1 Comment

I knew it, I want to not write anything in View

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.