Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call javascript on angular 2

I have javascript file from assets/js/chartrank.js

chartrank.js

function chartRank() {
    // do something
}

and call a function defined in it on rankuser component but it doesn't work.

rankuser.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import "../../assets/js/chartrank.js";
declare var jsObject: any;

@Component({
  selector: 'app-rankuser',
  templateUrl: './rankuser.component.html',
  styleUrls: ['./rankuser.component.css']
})
export class RankuserComponent implements OnInit, AfterViewInit {

  constructor() { }

  ngAfterViewInit() {
    jsObject.chartRank();
  }

  ngOnInit() {

  }
}

ERROR

ERROR ReferenceError: jsObject is not defined

Please help.

like image 937
nguyenhuyenag Avatar asked Mar 06 '23 13:03

nguyenhuyenag


1 Answers

import doesn't work here because chartrank.js doesn't export anything.

The simplest way here is adding chartrank.js to .angular-cli.json's scripts array, and declare the chartRank(function name) as a global variable.

.angular-cli.json

"scripts": [
  "./assets/js/chartrank.js"
],

component or service

declare var chartRank: any;

@Component({
  ...
})
export class RankuserComponent implements OnInit, AfterViewInit {

  ...

  ngAfterViewInit() {
    chartRank();
  }
}
like image 98
Pengyy Avatar answered Mar 16 '23 18:03

Pengyy