Angular 8 and jQuery: want to call a function

Viewed 62

I want to call a function clicking on dynamically generated URLs.

var push_div = '<a href="javascript:void(0)" onclick="myFunc('1')">Hello1</a></div>' + '<a href="javascript:void(0)" onclick="myFunc('2')">Hello2</a></div>';

myFunc(e) {
  console.log(e);
}

But I received an error:

Uncaught ReferenceError: myFunc is not defined

Then I modified my code as like:

var push_div = '<a id="1" href="javascript:void(0)">Hello1</a></div>' + '<a id="2" href="javascript:void(0)">Hello2</a></div>';


$(document).on('click', $(push_div).find('a').eq(0), function() {
  // my code
});

This is not console me any error however, I cannot detect which hyperlink I clicked. Any idea?

1 Answers

You can check the id property of the link which is clicked and call functions based on the different id. Here is the demo

here is the quick explanation,

All you need to do is,

Prepare HTML data inside your component file.

var push_div =
      '<a id="1" href="javascript:void(0)">Hello1</a></div>' +
      '<a id="2" href="javascript:void(0)">Hello2</a></div>';

Grab a reference of a div in which you want to append this HTML data.

const div = document.getElementById("wrapper");
$(div).html(push_div);

add the click event listener on the newly created anchor tags,

$(div).find('a').on("click", ev => {
      switch (ev.target.id) {
        case "1":
          this.myFunction1();
          break;
        case "2":
          this.myFunction2();
          break;
      }
    });

That's it. By the way, you may want to do this inside your angular app but actually this logic has nothing to do with an angular app. this is a pure javascript thing. I hope this will help.

Here I would like to share the whole component file.

import { Component, AfterViewInit } from "@angular/core";
import $ from 'jquery';

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements AfterViewInit {
  name = "Angular";

  ngAfterViewInit(): void {
    const div = document.getElementById("wrapper");

    var push_div =
      '<a id="1" href="javascript:void(0)">Hello1</a></div>' +
      '<a id="2" href="javascript:void(0)">Hello2</a></div>';

    $(div).html(push_div);

    $(div).find('a').on("click", ev => {
      switch (ev.target.id) {
        case "1":
          this.myFunction1();
          break;
        case "2":
          this.myFunction2();
          break;
      }
    });
  }

  myFunction1() {
    alert(1);
  }

  myFunction2() {
    alert(2);
  }
}
Related