0

I have a function X within a JavaScript file “MyFile.js” in the following path of an Angular 4 project : /assets/js/MyFile.js

I already added the path in the angular-cli.json into the scripts section.

...
“scripts”:
[ “assets/js/MyFile.js”]
...

Question: How can access the function X in MyFile.js from a typescript component?

1

1 Answer 1

0

I don't believe that you can call a function from a script added via .angular-cli.json, although you can implement IIFEs that way. Normal usage is for external libraries (bootstrap.js, collapse, animations and the like) as they get added as <script> tags in the index.html.

Rather than adding it to your angular-cli.json, it's easier to import it in your components

  1. Give MyFile a .ts extension to avoid having to pass the --allowJs flag. E.g., MyFile.ts
  2. Make sure to export your functions. If you have several, you might put them in a class and make them static (but that's a different question). Here's what I did:

_

// myfile.ts
export const myFunction = () => {
  console.log('hello');
};

_

  1. Import the script into the desired component via import { myFunction } from '../assets/js/myFunction'

_

import { Component, OnInit } from '@angular/core';  
import { myFunction} from '../assets/js/myfile';

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


export class AppComponent implements OnInit {
  title = 'app';

  ngOnInit() {
    myFunction();
  }
}

_

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.