问题
I am working on an Angular CLI Project where I need to call some jQuery functions.
I have included my js in the angular.json file:
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"src/custom.js"
]
jQuery function:
function A() { alert('A'); }
function B() { alert('B'); }
I have imported jQuery in my component where I need to call these jQuery functions :-
import * as $ from 'jquery';
tsconfig.app.json :
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"allowJs": true,
"baseUrl": "./",
"module": "es2015",
"types": []
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}
Now, how to import custom.js in my component and how to call these functions A & B?
回答1:
I recommend installing the types for jquery if you haven't done so already:
npm install --save @types/jquery
So you can simply use it by just importing jQuery (jquery
) in your component/service:
import 'jquery';
When you have problems compiling or build
ing your application, it can be solved by wrapping your selector in (<any> ...)
or (... as any)
:
// Use this
(<any> $('.myElement')).A();
// or this
($('.myElement') as any).A();
Update (see comments)
To execute code after page is ready, try implementing AfterViewInit
to your main component (app-root
):
import { Component, OnInit, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, AfterViewInit {
constructor(private someService: SomeService) { }
ngAfterViewInit() {
this.someService.someFunction();
}
}
documentation for AfterViewInit
来源:https://stackoverflow.com/questions/50606429/how-to-call-an-external-jquery-functions-in-angular