Angular 2: import external js file into component
I'm going to import this d3gauge.js file into one of my angular2 component, memmon.component.ts
file.
import '../../../../js/d3gauge.js';
export class MemMonComponent {
createMemGauge() {
new drawGauge(this.opt); //drawGauge() is a function inside d3gauge.js
}
}
and in the corresponding template file, add
<script src="../../../../js/d3gauge.js"></script>
But it doesn't work, drawGauge
can't be found.
So,
- what're correct steps to import an external js file to angular2?
- since I'm using webpack, is it possible to do it in webpack? I refer to this question , the webpack solution there doesn't work for me as a result of
.ensure
can't be resolved.
Solution 1:
Ideally you need to have .d.ts
file for typings to let Linting
work.
But It seems that d3gauge
doesn't have one, you can Ask the developers to provide and hope they will listen.
Alternatively, you can solve this specific issue by doing this
declare var drawGauge: any;
import '../../../../js/d3gauge.js';
export class MemMonComponent {
createMemGauge() {
new drawGauge(this.opt); //drawGauge() is a function inside d3gauge.js
}
}
If you use it in multiple files, you can create a d3gauage.d.ts
file with the content below
declare var drawGauge: any;
and reference it in your boot.ts
(bootstrap) file at the top, like this
///<reference path="../path/to/d3gauage.d.ts"/>
Solution 2:
After wasting a lot of time in finding its solution, I've found one. For your convenience I've used the complete code that you can replace your whole file with.
This is a general answer. Let's say you want to import a file named testjs.js into your angular 2 component. Create testjs.js in your assets folder:
assets > testjs.js
function test(){
alert('TestingFunction')
}
include testjs.js in your index.html
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Project1</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="./assets/testjs.js"></script>
</head>
<body>
<app-root>Loading...</app-root>
</body>
</html>
In your app.component.ts or in any component.ts file where you want to call this js declare a variable and call the function like below:
app.component.ts
import { Component } from '@angular/core';
declare var test: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
f(){
new test();
}
}
Finally in your app.component.html test the function
app.component.html
<h1>
<button (click)='f()'>Test</button>
</h1>