1

Let's just say I make a custom JavaScript file ie 'custom.js'

How would I implement this into a Component?

If I add 'custom.js' to index.html, that's fine but is there any way I can add it specifically to the component?

Brian
  • 4,921
  • 3
  • 20
  • 29

3 Answers3

6

Step: 1=> Create and write your js code say "synapse.js" in /app folder. The function or constant which you to use in a component should be exported using export keyword. for ex:

synapse.js

export function synapseThrow() {
  return 'hello'
}

export const MY_VAR = 'world!';

Step: 2=> in angular-cli.json, add the below part in apps object.

"scripts": ["app/synapse.js"]

Step: 3=> in tsconfig.json, add the below property in compilerOptions.

"allowJs": true

Step: 4=> in any component say in "app.component.ts" import the "synapse.js" file using import keyword.

app.component.ts

// other imports

import { MY_VAR, synapseThrow } from './synapse';

// other app code here

ngOnInit(){
  const returned = MY_VAR;
  const returnFunc = synapseThrow();
}
solanki...
  • 4,982
  • 2
  • 27
  • 29
1

Try this way:

  • Put js file in path: assets/js/custom.js
  • Code your component

ts file

export class MyComponent implements AfterViewChecked {
  constructor(private elementRef: ElementRef) {

  }
  ngAfterViewChecked() {
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "../assets/js/custom.js";
    this.elementRef.nativeElement.appendChild(s);
  }
}
IZI
  • 91
  • 1
  • 3
0

Try declaring a variable that you have inside of your custom.js file


declare var aFunction: any;

import '../../../js/custom.js';

export class ExampleComponent{

    variable: any;

    constructor() { }

    ngOnInit() { 
       new aFunction(this.variable);  //aFunction() is inside custom.js
    }
}
Joaquin Diaz
  • 184
  • 1
  • 5
  • 16