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

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

6 Comments

Yes I need use angular 2
@alehn96 - not with the code above you don't. Nothing in $('#myModal').modal('show') uses anything specific to angular2.
Thanks, so I have to create method in component and when the event is invoked, then use jquery, is only way?
@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.
How I use jquery in template of a component?
|
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.

1 Comment

Thanks, I resolve with that $(this.elRef.nativeElement).find('#myModal').modal('show'); in the component where elRef:ElementRef

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.