canmustu
canmustu

Reputation: 2649

How to Use External Javascript in TypeScript Angular


I want to use jquery and easypiechart js file's functions in typescript.

It doesn't work this way.

How to define these script what i specified in code as typescript ?


index.component.ts

import { Component, OnInit } from '@angular/core';

import * as $ from "../../../../../assets/plugins/jquery/jquery.min.js";
import { easyPieChart } from "../../../../../assets/plugins/easypiechart/jquery.easypiechart.min.js";

// these above 2 js files are defined in angular.json script section

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss']
})

export class IndexComponent implements OnInit {

  constructor() {}

  ngOnInit() {

    //$(function(){
    //  $('.easypiechart').easyPieChart();
    //});

    // How to write this above script as typescript ?????????????????????

  }
}

Upvotes: 1

Views: 8672

Answers (4)

Hameed Syed
Hameed Syed

Reputation: 4275

From the above question,it looks like jquery.easypiechart.min.js is the one that you need to use in your angular application as external js.

  1. Put the js under assets folder say /assets/js/jquery.easypiechart.min.js
  2. Goto your projects angular.json file and under scripts node of architect node put as an entry in the array.

    "scripts": [ "./node_modules/jquery/dist/jquery.min.js",
    "./src/assets/js/jquery.easypiechart.min.js" ]

Now you can refer the external js in any of your projects components

  declare var $: any;// referencing jQuery library
    @Component({
      selector: 'app-index',
      templateUrl: './index.component.html',
      styleUrls: ['./index.component.scss']
    })

    export class IndexComponent implements OnInit {
      constructor() {}
      ngOnInit() {
      $(document).ready(function () {
          //accessing easypiechart.min.js.
          $('.easypiechart').easyPieChart();
         });
      }
    }

Upvotes: 2

Daniel
Daniel

Reputation: 286

Normally you don't want to use jquery in Angular, because it usually implies to modify directly the DOM, which is a bad practice, but there is the way to do it: https://medium.com/all-is-web/angular-5-using-jquery-plugins-5edf4e642969

If you wanna plot a pie chart or other types of charts, you could use ng2-charts instead, it will allow you to use charts.js with Angular and Typescript.

Upvotes: 0

brk
brk

Reputation: 50346

Instead of putting it in asset folder you should use it as node_modules dependency

For easy pie chart run this npm i easy-pie-chart --save & for jquery run npm i jquery

Upvotes: 0

Dhananjai Pai
Dhananjai Pai

Reputation: 6005

If you have included them in the scripts or index.html, you don't have to import them to the .TS file again

Use declare instead and it should work What does 'declare' do in 'export declare class Actions'?

Upvotes: 2

Related Questions