0

How use JQuery in template in component of Angular 2?

Example

import { Component } from '@angular/core'  
import * as $ from 'jquery';
...

in template of the component use

<p (click)="$('#myModal').modal('show');">show</p>

it return this error

ERROR TypeError: co.$ is not a function {}

alehn96
  • 1,363
  • 1
  • 13
  • 23
  • possible duplicate of http://stackoverflow.com/questions/30623825/how-to-use-jquery-with-angular2 – warl0ck Apr 18 '17 at 17:40

2 Answers2

1

Don't go through the angular framework if you do not need it.

<p onclick="$('#myModal').modal('show');">show</p>

By trying to use (click) the references are resolved based on the containing angular component so angular attempts to resolve $ as an instance on that component.

Alternatively you have to create a method in your component that then calls through to jquery. This method is then called from the template using (click).

Igor
  • 60,821
  • 10
  • 100
  • 175
  • Yes I need use angular 2 – alehn96 Apr 18 '17 at 17:49
  • @alehn96 - not with the code above you don't. Nothing in `$('#myModal').modal('show')` uses anything specific to `angular2`. – Igor Apr 18 '17 at 17:50
  • Thanks, so I have to create method in component and when the event is invoked, then use jquery, is only way? – alehn96 Apr 18 '17 at 17:52
  • @alehn96 - correct. Either: register to `onclick`. Use angular's `(click)` and have the `jquery` call inside the method in your component. Or create a new angular directive that registers to `click` and executes the jquery code. – Igor Apr 18 '17 at 17:54
  • How I use jquery in template of a component? – alehn96 Apr 18 '17 at 17:55
  • Thanks, I resolve with that $(this.elRef.nativeElement).find('#myModal').modal('show'); in the component where elRef:ElementRef – alehn96 Apr 18 '17 at 19:10
0

Build a custom directive that will communicate with jquery.

@Directive({selector:'[trigger]'})
export class TriggerModelDirective {

  constructor(private el: elementRef) {
  }

  onInit() {
    this.el.nativeElement.addEventListener(()=> {
       $('#myModal').modal('show');
  });
}

You might need to add removeEventListener and also wrap $ into opaque token for Angular.

Julia Passynkova
  • 17,256
  • 6
  • 33
  • 32
  • Thanks, I resolve with that $(this.elRef.nativeElement).find('#myModal').modal('show'); in the component where elRef:ElementRef – alehn96 Apr 18 '17 at 19:50