0
votes

I am very new to angular and front end web development, so maybe i am missing something basic but i did not succeed to search a solution for that issue.

according to that answer: Call pure javascript function from Angular 2 component

and following that example

I am trying to import external .js file to my angular component:

import '../../../src/Plugin/codemirror/mode/custom/custom.js'

@Component({
    selector: 'txt-zone',
    templateUrl: 'app/txtzone/Txtzone.component.html',
    styleUrls: ['app/txtzone/TxtZone.css'],


})

the path is the correct relative path, i know that because if it loads diractly from the url text box via the browser [http://localhost:50371/src/Plugin/codemirror/mode/custom/custom.js] i can see the file content...

this is the exception that the chrome debugger is throwing:

zone.js:2263 GET http://localhost:50371/src/Plugin/codemirror/lib/codemirror 404 (Not Found)

as you can see the path was changed (don`t understand why?)

1. how can i solve this issue?
2. why the path of the .js file is not the referenced path?
3. maybe there is a better way to load external .js file into my component?

it looks quite trivial question but after hours of searching i could not find any answer.

1
check this LINK it has a question related to importing js using types and without typesAlos you can look at this answer - Rahul Singh

1 Answers

3
votes

A simple way to include custom javascript functions in your Angular 4 project is to include the item in your assets folder, and then use require to import it into your component typescript.

src/assets/example.js

export function test() {
    console.log('test');
}

src/app/app.component.ts

(before @Component(...))

declare var require: any;
const example = require('../assets/example');

(inside export class AppComponent implements OnInit { ...)

ngOnInit() {
  example.test();
}