1

I want to trigger click event based on each element id but it is not working.

Here is my code:

ngOnInit() {
  this.getProductsLists();
}

getProductsLists() {
  this.supplierService.getProductLists()
    .subscribe(data => {
      this.productData = data;
      this.productData.forEach((value) => {
        value.prodCategoryChild.forEach((element) => {
          $('#prod' + element.id).click(() => {
            alert('This is not working');
          })
        });
      });
    });
}

What am I missing here? Thanks.

9
  • Where you calling this code? In constructor? Commented Sep 28, 2018 at 6:55
  • I am calling it on ngOnInit() Commented Sep 28, 2018 at 6:57
  • and UI is fully rendered? Commented Sep 28, 2018 at 6:59
  • 1
    Why not just handle click from html template? Commented Sep 28, 2018 at 7:02
  • 2
    First up, you shouldn't be using jQuery for accessing the DOM in Angular in the first place. Second, you can use *ngFor in your template and bind to the click event of each item and pass the id or index as an argument to the function that you'll be calling as your click handler. Commented Sep 28, 2018 at 7:06

1 Answer 1

1

An Angular way should be like this:

<div-or-whatever (click)="clickHandler(prod.id)" *ngFor="let prod of productData" >{{ prod.label }}</div-or-whatever>

then

clickHandler(id) {
    alert(`Clicked prod ${id}`);
}
Sign up to request clarification or add additional context in comments.

Comments

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.