Jquery not working in Angular 2

Hi ,
Here is my code

my-component.html // this is Angular 2 component html

<a href="#" title="Create New" id="Btn" class="fa fa-plus-circle FA_Ico"></a>

external.js // this is an external js file which is imported into index.html

$("#Btn").on('click', function (evt) {  // Jquery is imported in index.html

When I click anchor in my-component.html … external js is not called and I dont get alert. I’ want to use Jquery in Angular whenever required. Whats the fix to this ?

I know angular has its own click handler…however I need to use Jquery event handler in the angular 2 code for some reason. Whats the workaround ?

Hi @winzip, I’m not sure what’s the problem but I would advise against including too many frameworks and libraries if there isn’t a really good reason. Therefore may I ask you what is the reason you’re trying to use jQuery together with Angular?

the existing UI html design page has Jquery bindings

for example ,

this is my Jquery code in external.js

$("#Btn").on('click', function (evt) { 
        $(this).parents().find('ul#breadcrumb').append('<li>Create </li>');        

Is there any angular 2 way to achieve the same effect ?

I have this sort of Jquery bindings in many places in HTML design.

How do I write this in angular 2 way ? can you please provide a sample if it is possible at all

The component that contains #Btn most probably hasn’t been rendered yet when you’re binding the event listener; try using event delegation instead. (BTW, because of the reusable nature of components I would suggest to avoid assigning IDs to elements here.)

That being said, you’d have to be extremely cautious not to interfere with Angular’s internal workings; otherwise you’ll likely end up with bugs that are hard to track down, not to mention that it’s hardly testable. Actually, better don’t do it in the first place.

The whole point is that you don’t have to manually query and manipulate the DOM at all, but rather describe how the data should be rendered in a declarative way. E.g. the above could (roughly) be written like

  selector: 'my-app',
  template: `
    <ul class="breadcrumb">
      <li *ngFor="let breadcrumb of breadcrumbs">{{breadcrumb}}</li>
    <button (click)="create()">Create new</button>
export class AppComponent  {
  private breadcrumbs = []

  create () {

(… although in a real app the breadcrumb would probably better be its own component.)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.