【发布时间】:2017-03-23 20:20:45
【问题描述】:
全部 我正在使用 Angular 2 制作一个小型 Web 应用程序,我想在其中使用 JQuery。 我在chrome中遇到错误我不知道为什么 这是错误:
core.umd.js:3004 EXCEPTION: Uncaught (in promise): Error: Error in `enter code here`http://localhost:3000/app/dashboard.component.js class DashboardComponent_Host - inline template:0:0 caused by: $ is not defined
ReferenceError: $ is not defined
at DashboardComponent.ngOnInit (http://localhost:3000/app/dashboard.component.js:22:9)
at Wrapper_DashboardComponent.detectChangesInInputProps (/AppModule/DashboardComponent/wrapper.ngfactory.js:18:53)
at _View_DashboardComponent_Host0.detectChangesInternal (/AppModule/DashboardComponent/host.ngfactory.js:30:32)
at _View_DashboardComponent_Host0.AppView.detectChanges (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:9305:18)
at _View_DashboardComponent_Host0.DebugAppView.detectChanges (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:9410:48)
at ViewRef_.detectChanges (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:7398:24)
at RouterOutlet.activate (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:3458:46)
at ActivateRoutes.placeComponentIntoOutlet (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:2955:20)
at ActivateRoutes.activateRoutes (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:2933:26)
at eval (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:2902:23)
这是我的代码:
import { Component, ElementRef, OnInit } from '@angular/core';
declare var $:JQueryStatic;
@Component({
moduleId: module.id,
selector: 'my-dashboard',
templateUrl: 'dashboard.component.html',
styleUrls: ['dashboard.component.css'],
})
export class DashboardComponent implements OnInit{
constructor(private elRef: ElementRef){}
ngOnInit():any{
$(this.elRef.nativeElement).find('button').on('click', function() {
alert('It works!');
});
}
}
我使用此答案安装 jquery 并按照说明进行了所有操作,但不起作用。 link 任何想法为什么? 谢谢
修复
我通过将 declare var $:JQueryStatic; 更改为 declare var $:any; 来修复它
并将<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script> 包含在index.html 中
【问题讨论】:
-
你试过类似
import $ from 'jquery';吗? -
@DanielD 我刚才做了,上面写着
Module "jquery" has no default export. -
这取决于您使用的打字稿版本。我认为他们已经不再需要打字了。您的问题可能与您链接的其他问题类似,但答案取决于您的技术版本。
标签: javascript jquery angular