17

I have a javascript file that contains some data manipulation functions (No DOM manipulation at all) such as float rounding, mathematical operations, ...etc

my js file called myexample.js looks like that

function example(input) {
  return input * 2
}
module.exports = { example: example }

and then I have my angular component example.component.ts

for example:

import { Component, EventEmitter} from '@angular/core';
@Component({
  selector: 'input-number',
  template: `<input 
              type='text' 
              [(value)]='value' 
              (blur)='runExample()' 
             />`,
  inputs: ['value'],
  outputs: ['valueChange']
})
export class Example {
  value: string;
  valueChange = new EventEmitter;

  runExample() {
    let val = parseFloat(this.value);
    // here i need to call example(input) from myexample.js
    // and assign the return to val
    this.valueChange.emit(val);
  }

I have been searching for quite a while now and tried multiple things but unfortunately with no luck at all.

I would be really grateful if someone can help.

4 Answers 4

19

You can export functions in TypeScript:

export function example(input) {
  return input * 2;
}

and use it this way (assuming your file name is lib.ts):

import {example} from './lib';

example();

If you want to use a CommonJS file, you need to configure SystemJS in the map attribute:

System.config({
  (...)
  map: {
    lib: 'path/to/lib/js'
  }
});

You can import your module the same way then:

import {example} from './lib';
Sign up to request clarification or add additional context in comments.

6 Comments

1- I have to use the javascript (can't convert it to typescript) file as it is shared between different projects
2- what about if I am using webpack?
okay. Make sense... I think that you can require directly the file with Webpack. Something like var lib = require('./path/to/lib');
I imported it by const lib = require('my/file/path') and then from inside the component i called lib.example(input) so now it is actually reading the file but I am getting this error Uncaught ReferenceError: example is not defined and the angular application is not running
If you use console.log(lib), what is printed in the js console?
|
2

this is what it worked for me I was trying to use html2pdf from an Angular2 app, so I had to make a reference to this function

var html2pdf = (function(html2canvas, jsPDF) {

declared in html2pdf.js.

So I added just after the import declarations in my angular-controller this declaration:

declare function html2pdf(html2canvas, jsPDF): any;

then, from a method of my angular controller I'm calling this function:

generate_pdf(){
    this.someService.loadContent().subscribe(
      pdfContent => {
        html2pdf(pdfContent, {
          margin:       1,
          filename:     'myfile.pdf',
          image:        { type: 'jpeg', quality: 0.98 },
          html2canvas:  { dpi: 192, letterRendering: true },
          jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
        });
      }
    );
  }

Hope it helps

1 Comment

Works for this module (it is not the only one named html2pdf)
2

Another way is to add your js functions defined in a separate file to a global scope. So in your js file you can add sth like this:

$(document).ready(function() {
    window.example = example;
}

Then in your component typeScript file, right below the imports, you can declare this function:

declare function example(input): void;

And then you can just simply use this function in the component methods.

Comments

-1

I finally found out the answer; it was to basically make a typings file and add it to the project.

The problem was related to TypeScript not Angular2. In typeScript you can't simply use any JS file without having a definition (typing) file that declares the types of the vars, the params of the functions, as well as the returns. check this link to know how to create one.

3 Comments

How did you do that exactly?
Please explain the steps of the solution that you found.
The problem was related to TypeScript not Angular2. In typeScript you can't simply use any JS file without having a definition (typing) file that declares the types of the vars, the params of the functions, as well as the returns. check this link to know how to create one. peter.grman.at/how-to-write-typescript-definition-files

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.