How to call an external jQuery functions in angular

若如初见. 提交于 2019-12-23 02:44:15

问题


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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!