ksz*_*dev 3 jquery mcustomscrollbar angular
我有一个问题,将这些模块导入我的angular2组件.我使用AngularClass的angular2-webpack-starter.
我用npm安装dependecies:
npm install jquery --save
npm install malihu-custom-scrollbar-plugin --save
Run Code Online (Sandbox Code Playgroud)
并安装打字:
typings install jquery --save --ambient
typings install mcustomscrollbar --save --ambient
Run Code Online (Sandbox Code Playgroud)
我想在这样的组件中使用它:
jQuery('.selector').mCustomScrollbar();
Run Code Online (Sandbox Code Playgroud)
这样做的最佳解决方案是什么?
我尝试使用这个解决方案:什么是在角度2内使用jquery小部件的最佳方法?
但它不起作用,我得到错误"jQuery没有定义".
使用
Angular:2.0.0
Typescript:2.0.2
Angular-cli:1.0.0-beta.16
webpack:2.1.0-beta.22
node:4.6
npm:2.15.9
解答
将类型添加到src/tsconfig.json
解
获取必需的包
npm install jquery malihu-custom-scrollbar-plugin --save
npm install @types/jquery @types/jquery-mousewheel @types/mcustomscrollbar --save-dev
将插件css和脚本添加到根文件夹中的angular-cli.json
//angular-cli.json
"apps": [
{
...,
"styles": [
...,
"../node_modules/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/malihu-custom-scrollbar-plugin/node_modules/jquery-mousewheel/jquery.mousewheel.js",
"../node_modules/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.concat.min.js"
],
...
}
]
Run Code Online (Sandbox Code Playgroud)将类型添加到src/tsconfig.json
//tsconfig.json
{
"compilerOptions": {
...,
"typeRoots": [
"../node_modules/@types/"
],
"types": [
"jquery","jquery-mousewheel","mCustomScrollbar"
],
...
}
}
Run Code Online (Sandbox Code Playgroud)制定指令
//scrollbar.directive.ts
import {Directive, ElementRef, OnInit} from '@angular/core';
declare var $:any; //<-- let typescript compiler know your referencing a var that was already declared
@Directive({
selector: 'scrollbar',
host: {'class':'mCustomScrollbar'}, //<-- Make sure you add the class
})
export class ScrollbarDirective implements OnInit {
el: ElementRef;
constructor(el:ElementRef) {
this.el = el;
}
ngOnInit() {
//$(function(){ console.log('Hello'); }); <--TEST JQUERY
//check if your plugins are loading
//$().mousewheel) ? console.log('mousewheel loaded') : console.log('mousewheel not loaded');
//$().mCustomScrollbar) ? console.log('mCustomScrollbar loaded') : console.log('mCustomScrollbar not loaded');
$(this.el.nativeElement).mCustomScrollbar({
autoHideScrollbar: false,
theme: "light",
advanced: {
updateOnContentResize: true
}
});
Run Code Online (Sandbox Code Playgroud)在ngModule中包含指令并应用于组件的模板中
//app.module.ts
import {ScrollbarDirective} from "./shared/UI/scrollbar.directive";
import {AppComponent} from "./app.component";
@NgModule({
...
declarations: [
AppComponent,
...,
ScrollbarDirective
],
...
})
export class AppModule{}
Run Code Online (Sandbox Code Playgroud)
//app.component.ts
@Component({
selector: 'dashboard',
templateUrl: `
<scrollbar>
<div *ngFor="let thing of things">thing</div><br/>
</scrollbar>
`
})
Run Code Online (Sandbox Code Playgroud)