如何以角度调用外部 jQuery 函数 [英] How to call an external jQuery functions in angular
问题描述
我正在开发一个 Angular CLI 项目,我需要在其中调用一些 jQuery 函数.
I am working on an Angular CLI Project where I need to call some jQuery functions.
我已将我的 js 包含在 angular.json 文件中:
I have included my js in the angular.json file:
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"src/custom.js"
]
jQuery 函数:
function A() { alert('A'); }
function B() { alert('B'); }
我已经在我需要调用这些 jQuery 函数的组件中导入了 jQuery :-
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"
]
}
现在,如何在我的组件中导入 custom.js 以及如何调用这些函数 A &乙?
Now, how to import custom.js in my component and how to call these functions A & B?
推荐答案
如果您还没有安装 jquery 的类型,我建议您这样做:
I recommend installing the types for jquery if you haven't done so already:
npm install --save @types/jquery
因此,您只需在组件/服务中导入 jQuery (jquery
) 即可简单地使用它:
So you can simply use it by just importing jQuery (jquery
) in your component/service:
import 'jquery';
<小时>
当您在编译或构建
应用程序时遇到问题,可以通过将选择器包装在 (<any> ...)
或 中来解决(......任何)
:
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();
<小时>
更新(见评论)
要在页面准备好后执行代码,请尝试将 AfterViewInit
实现到您的主要组件 (app-root
):
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();
}
}
这篇关于如何以角度调用外部 jQuery 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!