Calling properly TypeScript code from JavaScript

后端 未结 5 1584
生来不讨喜
生来不讨喜 2020-12-03 11:36

On our big enterprise project we faced a situation that seems not to be very well described in the articles and the posts available in the Internet.

We need to integ

5条回答
  •  盖世英雄少女心
    2020-12-03 12:37

    This actually not all too complicated. . . the first thing you have to understand is that the component is created as an object by angular, and it contains all the data, components, objects and stuff from your api's so you can't just go have JavaScript make a new one, it will be empty and won't actually have your form data in it.

    In order to remedy this, you need to add an asset to your site, a simple file with one variable in it is fine, then add it to your app, then import it and set it in your init

    i've outlined how you import a JS variable into angular below, but here's a link with a bit more detail:
    How to call JavaScript functions from Typescript in Angular 5?

    so add the js file containing:

    var formComponent = null;
    

    then add it to your app (angular.json)

    "scripts": [
        "src/assets/js/formScripting.js"
    ]
    

    then import it to your component right under your "imports"

    declare var formComponent: any;
    

    then assign your object on your init and destroy

    ngOnInit() {
        formComponent = this; 
    }
    
    ngOnDestroy(): any {
        formComponent = null;
    }
    
    
    //a function in your class that you want to call for test purposes
    doAngularThing() {
        console.log('Typescript called from JS:')
    }
    

    from that point on, in ANY javascript function all you have to do is call:

    formComponent.doAngularThing();
    

    since the formComponent object was assigned to this, it's a pointer to the angular object that loaded your compoonent

提交回复
热议问题