如何在angular中调用外部jQuery函数 [英] How to call an external jQuery functions in angular

查看:98
本文介绍了如何在angular中调用外部jQuery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个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& B?

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'; 


在编译或build应用程序时遇到问题时,可以通过将选择器包装在(<any> ...)(... as any)中来解决:


When you have problems compiling or building 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();


更新(请参阅评论)

要在页面准备就绪后执行代码,请尝试对主要组件(app-root)实施AfterViewInit:

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();
  }
}

AfterViewInit的文档

这篇关于如何在angular中调用外部jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆