Home > Blockchain >  Is it possible to use Index.html functions inside my Angular project
Is it possible to use Index.html functions inside my Angular project

Time:04-16

I have some functions inside my index.html file that uses window. I can open the index.html on it's own and use the said methods in my browser console and they work as intended. However I would like to be able to use these methods in my angular project. So, for an example, inside my app.component.ts file. I've tried starting to move the functions from the index.html file to my app.component.ts file just to try them out but it's quite large codebase and if it's possible I would want to be able to use them without moving them from the file. Below is an example of how the index.html file looks like.

    <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Project</title>
    <base href="/" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
   
   <link>*Here are alot of urls. nothing important*</link

  </head>
  <body>
    <script type="text/javascript">
      
      window.getCars = function (param1) {
        doesSomething...
      };

      window.getCarBrand = function (param1, param2) {
        doesSomething...
      };
 
    </script>
    <app-root></app-root>
  </body>
</html>

I'm trying to use these methods in my angular project but I can't seem to figure out how I reference window correctly. I've tried using the suggestion from this post. But I can't seem to figure it out.

What I want to be able to do in the end is to use windows.getCars() in my app.component.ts file from my index.html file by utilizing window.

My Angular version is: 13.2.7

tl;dr how do I use methods that are in the index.html file in my angular project.

CodePudding user response:

Although it's not advised, you can simply create a dedicated service for that.


@Injectable({ providedIn: 'root' })
export class WindowBinderService {

  constructor() {
    window.functions = this;
  }

  getCars() { /* ... */ }
  getCarBrand() { /* ... */ }
}


You can then call it with window.functions.getCars() from anywhere (minus the typing errors).

CodePudding user response:

While temp_user suggestion would work. I solved this by temporally adding //@ts-ignore. Before making a function call. This lets me use all of my functions declared globally in my index.html file from anywhere. You shouldn't do this however but it works for now.

  • Related