簡體   English   中英

如何在 TypeScript Angular 中使用外部 Javascript

[英]How to Use External Javascript in TypeScript Angular


我想在打字稿中使用 jquery 和 easypiechart js 文件的函數。

這種方式行不通。

如何定義我在代碼中指定為打字稿的這些腳本?


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 ?????????????????????

  }
}

如果您已將它們包含在腳本或 index.html 中,則不必再次將它們導入到 .TS 文件中

改用declare ,它應該可以工作“聲明”在“導出聲明類操作”中有什么作用?

從上面的問題來看,看起來jquery.easypiechart.min.js是您需要在 angular 應用程序中作為外部 js使用的那個。

  1. 將js放在assets文件夾下說/assets/js/jquery.easypiechart.min.js
  2. 轉到您的項目angular.json文件並在架構師節點的腳本節點下作為數組中的條目放置。

    "腳本": [ "./node_modules/jquery/dist/jquery.min.js",
    “./src/assets/js/jquery.easypiechart.min.js” ]

現在您可以在任何項目組件中引用外部 js

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

您應該將其用作node_modules依賴項,而不是將其放在資產文件夾中

為了簡單的餅圖運行這個npm i easy-pie-chart --save & for jquery run npm i jquery

通常你不想在 Angular 中使用 jquery,因為它通常意味着直接修改 DOM,這是一個不好的做法,但有辦法做到: https : //medium.com/all-is-web /angular-5-using-jquery-plugins-5edf4e642969

如果你想繪制餅圖或其他類型的圖表,你可以使用NG2-圖表相反,它可以讓你使用charts.js與角和打字稿。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM