Home > Software design >  How to call a method from a JS file into an Angular component
How to call a method from a JS file into an Angular component

Time:03-29

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.

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.

CodePudding user response:

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

  • Related