alehn96
alehn96

Reputation: 1393

How use jquery in template of Angular 2?

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 {}

Upvotes: 0

Views: 1550

Answers (2)

Julia Passynkova
Julia Passynkova

Reputation: 17879

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.

Upvotes: 0

Igor
Igor

Reputation: 62213

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).

Upvotes: 1

Related Questions