Home > Back-end >  use JavaScript function in angular app.component.ts
use JavaScript function in angular app.component.ts

Time:11-12

i have a js file action.js and i want to use javaScript in angular. so when i read about it, it says that js file must be put in assets and the path must be refered in scripts array in angular.json and then using declare in ts and ngOnInit but this raises an error that the function is undefined beside that is forbidden to access the js file and MIME type checking is enabled

here is my js file function

function Di(){
    console.log('ffffffffffffff');
}

the app.component.ts

import { AstMemoryEfficientTransformer } from '@angular/compiler';
import { Component, OnInit } from '@angular/core';
declare function Di(): any;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
  title = 'Calculator';

  ngOnInit() { 
    Di();
  }
}

angular.json

"styles": [
              "src/styles.scss"
            ],
            "scripts": ["src/assets/js/action.js"]
          },

app.component.html

    </div>
</div>

  <script src = "/src/assets/action.js"></script>
</body>

thanks in advance

want to use js functions in angular

CodePudding user response:

Try to create a di.ts file and export your function inside

export default function Di(){}

then import it into your AppComponent

import Di from 'di'

CodePudding user response:

Create a ts file instead of js and then create your function like this

export fuction Di() { console.log('Di') }

then import it into your component.

If this works for you I would like you to inform me, please.

  • Related