Skip to content
Advertisement

Unable to call a JS function from Typescript in Angular 13

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.:

  1. Also, I tried using require, but it also failed.

  2. I already tested previous solutions with an older version of Angular:

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,

enter image description here

Note: If unable to load the file from node_modules, please put that in regular folder like asset and do the import as suggested

Advertisement