How to use jQuery Plugin with Angular 4?
I want to use a range slider in an angular project and I tried using one available module for angular 4.
It works fine during compilation but when I try to build it for deployment, it throws the below error.
I checked for the option of using jQuery plugin directly in the angular project and I'm only getting options for doing it in Angular 2.
Is there any way we can use jQuery plugins in Angular 4?
Please let me know.
Thanks in advance!
Solution 1:
Install jquery with npm
npm install jquery --save
Add typings
npm install --save-dev @types/jquery
Add scripts to angular-cli.json
"apps": [{
...
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
],
...
}]
Build project and serve
ng build
Hope this helps! Enjoy coding
Solution 2:
Yes you can use jquery with Angular 4
Steps:
1) In index.html
put below line in tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
2) In component ts file below you have to declare var like this
import { Component } from '@angular/core';
declare var jquery:any;
declare var $ :any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular 4 with jquery';
toggleTitle(){
$('.title').slideToggle(); //
}
}
And use this code for corresponding html file like this:
<h1 class="title" style="display:none">
{{title}}
</h1>
<button (click)="toggleTitle()"> clickhere</button>
This will work for you. Thanks
Solution 3:
Install jQuery using NPM Jquery NPM
npm install jquery
Install the jQuery declaration file
npm install -D @types/jquery
Import jQuery inside .ts
import * as $ from 'jquery';
call inside class
export class JqueryComponent implements OnInit {
constructor() {
}
ngOnInit() {
$(window).click(function () {
alert('ok');
});
}
}