Angular : onClick on html element according to its class

Issue

Under my Angular App, I’m using some 3rd library widget which is rendering in my component.

My template is:

<div>
  <myWidGet></myWidGet>
</div>

Inside myWidGet there some button element that I want handle their events.
The button have those classes : .dx-edit-row .dx-command-edit .dx-link-save

so i i do that :

export class myClass AfterViewInit { 

  constructor(private elRef: ElementRef){}

  ngAfterViewInit() {
    this.elRef.nativeElement.querySelector('.dx-edit-row .dx-command-edit .dx- 
link-save').on('click', (e) => {
      alert('test');
    });
  }

}

My purpose is to get reference to my button and handle the click event from it.

Suggestions?

Solution

Normally the 3rd party widget should provide a click handler like so:

<myWidGet (click)="myFunction($event)"></myWidGet>

and in the controller:

myFunction(evt) {
  const target = evt.target
  console.log('test')
}

However, if they do not expose click handlers then I would seriously consider not using the widget.

If want to use the widget anyway then do this using jQuery:

ngAfterViewInit() {
  $('.dx-edit-row.dx-command-edit.dx-link-save').on('click', (evt) => {
    const target = evt.target
    console.log('test')
  });
}

The above assumes ALL these classes are present on the same button.

Or just use vanilla JS.

If the buttons are not available on ngAfterViewInit() then you could do this:

ngAfterViewInit() {
  const interval = setInterval(() => {
    const button = $('.dx-edit-row.dx-command-edit.dx-link-save')
    // if button is ready
    if (button) {
      // add click handlers
      button.on('click', (evt) => {
        const target = evt.target
        console.log('test')
      });
      // stop polling
      clearInterval(interval)
    }
  }, 100)
}

Answered By – danday74

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.