I’m trying to call the following function, LoadMultiSelect()
, from one of my components because I am using a non-Angular library:
https://ibnujakaria.github.io/multiple-select-js/
This works perfectly in the console:
new MultipleSelect('#select-multiple-language', { placeholder: 'Select Language' })
And loads the JS component.
Later, I try adding it in Angular, but I cannot find how to.
I tried to export the JS function in two ways:
export default function LoadMultiSelect() { new MultipleSelect('#select-multiple-language', { placeholder: 'Select Language' }); }
And like this:
LoadMultiSelect() { new MultipleSelect('#select-multiple-language', { placeholder: 'Select Language' }); } var multiselect = new LoadMultiSelect(); export { multiselect };
I created a file to load the exported function:
assets/js/multiselect.js
Later, I added it in my build
in the scripts
section from my angular.json
like this:
"scripts": [ "./node_modules/multiple-select-js/dist/js/multiple-select.js", "src/assets/js/multiselect.js" ]
And then I tried to add it in my component like this:
import LoadMultiSelect from '../../../../../assets/js/multiselect'; import LoadMultiSelect from 'src/assets/js/multiselect';
But nothing works, I get this error:
Could not find a declaration file for module ‘../../../../../assets/js/multiselect’. ‘/Users/fanmixco/Documents/GitHub/holma-bootstrap/src/assets/js/multiselect.js’ implicitly has an ‘any’ type.
Or others, any idea what I’m doing wrong?
P.S.:
Also, I tried using
require
, but it also failed.I already tested previous solutions with an older version of Angular:
- Unable to call javascript function from Typescript in Angular 6
- How to call JavaScript functions from Typescript in Angular 5?
- calling javascript function from typescript angular 2
Advertisement
Answer
I just tried this in my local system, with some random file like below,
export function MultipleSelect(val1, val2){ console.log('Be awesome always', val1, ' and ', val2); }
now I import this in my component like this,
export class AppComponent { title = 'stackoverflow-examples'; declare MultipleSelect: any; constructor( private fb: FormBuilder ) { } ngOnInit() { import('./someRandomFile').then(randomFile=>{ randomFile.MultipleSelect('one', 'two') }); } }
In order for this file to be imported in the angular ts file, I must allow it in tsconfig.json
by allowing the js import as given below,
"allowJs": true
see the result in the console below,
Note: If unable to load the file from node_modules, please put that in regular folder like asset
and do the import as suggested