Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a method from a JS file into an Angular component

This question doesn’t have any accepted answer and also It is related to AngularJS. I need a solution for Angular. None of the answer on the internet is working. My code is as follows:

Columns.js

export class Columns {
  getAllColumns() {
    return [
      {
        headerName: 'My Header',
        field: 'My field',
        filter: 'some filter',
        menuTabs: 'firsttab'
      },
      {...}... similar 3, 4 objects
    ]
  }

I need something like code below to assign this.fetchedCols returned columns.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my-component.component.ts

...
ngOnInit() {
  this.fetchedCols = Columns.getAllColumns(); // ERROR
}

I tried these steps also from this blog:

  • Step 1: Create a js named directory inside the assets directory and put the JavaScript (Columns.js) file inside it.
  • Step 2: Open the index.html and add a script tag to add the JavaScript file.
  • Step 3: Open the component where you want to use this JS file.
    Add below line to declare a variable:

declare var getAllColumns: any;

Use below line to call the function:

new getAllColumns();

Both the files (JS and Component) are in the same folder. I’m getting error:

ERROR TypeError: this.getColumnsDefs is not a function

Please help.

>Solution :

You should instantiate Columns object first, try this:

const columns = new Columns();
this.fetchedCols = columns.getAllColumns(); 

Columns object should be imported from a file where Columns is declared. But if you are using vscode or any other IDE you should be able to do that by hitting ctrl + space after Columns word

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading