当我的angular组件生成完成后,我需要使用jquery函数。我找到了下面的用法,但我不能让它工作。
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { Http } from '@angular/http';
declare var $:any;
@Component({
selector: 'nav-menu',
template: require('./NavMenu.component.html')
})
export class NavMenuComponent implements AfterViewInit {
@ViewChild('selectElem') el: ElementRef;
public navigation: IMenuItem[];
constructor(http: Http) {
http.get('http://localhost:52908/api/PageManager/Get?applicationID=3')
.subscribe(res => this.navigation = res.json().TransactionResult);
}
ngAfterViewInit(): any {
$(this.el.nativeElement).find('nav ul').jarvismenu({
accordion: true,
speed: true,
closedSign: '<em class="fa fa-plus-square-o"></em>',
openedSign: '<em class="fa fa-minus-square-o"></em>'
});
}
}
export interface IMenuItem {
PageID: number;
Code: string;
ApplicationID?: number;
DisplayText: string;
IconPath: string;
ParentID?: number;
IsFolder: boolean;
IsDefault: boolean;
ParentPage?: IMenuItem;
ChildPages: IMenuItem[];
BreadCrumb: string;
}
当我运行这段代码时,我得到一个错误:$没有定义。我试着用一个数字变量,它给出了同样的错误。似乎我不能在类之外声明任何东西。
顺便说一句,我也在用webpack。
谢谢。
发布于 2016-12-09 13:35:46
只需将JQuery代码包装到try catch中可能会对您有所帮助,也可以在使用$之前声明。
ngAfterViewInit(): any {
try{
$(this.el.nativeElement).find('nav ul').jarvismenu({
accordion: true,
speed: true,
closedSign: '<em class="fa fa-plus-square-o"></em>',
openedSign: '<em class="fa fa-minus-square-o"></em>'
});
}
catch(exception){}
}发布于 2016-12-09 13:59:44
当你使用webpack的时候,你应该告诉它将$设置为全局变量。我找到了这个解决方案:
安装expose-loader。在您的供应商文件(或用于导入jquery的任何其他文件)中键入
import 'expose?jQuery!jquery';在“webpack插件”一节中使用ProvidePlugin
new webpack.ProvidePlugin({ jQuery: 'jquery', $: 'jquery', jquery: 'jquery' })
发布于 2017-06-16 20:55:27
你检查过InjectionToken了吗?基本上,您将在应用程序中注入全局jQuery实例。就像这篇文章中看到的:Use jQuery in Angular/Typescript without a type definition。
您将创建一个jQueryService.ts,它将定义全局实例。
import { InjectionToken } from '@angular/core';
export const JQ_TOKEN = new InjectionToken('jQuery');
export function jQueryFactory() {
return window['jQuery'];
}
export const JQUERY_PROVIDER = [
{ provide: JQ_TOKEN, useFactory: jQueryFactory },
];必要时,您需要将其导入到app.module.ts中
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { JQ_TOKEN } from './jQuery.service';
declare let jQuery: Object;
@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent
],
providers: [
{ provide: JQ_TOKEN, useValue: jQuery }
],
bootstrap: [AppComponent]
})
export class AppModule { }以便您可以在component.ts中使用它
import { Component, Inject } from '@angular/core';
import { JQ_TOKEN } from './jQuery.service';
@Component({
selector: "selector",
templateUrl: 'somefile.html'
})
export class SomeComponent {
constructor( @Inject(JQ_TOKEN) private $: any) { }
somefunction() {
this.$('...').doSomething();
}
}https://stackoverflow.com/questions/41053649
复制相似问题