• Home
  • Jobs
  • Courses
  • Teachers
  • For business
  • Blog
  • ES/EN

0

31
Views
How to call JavaScript functions from Typescript in Angular 5?

I'm working on PDF Viewer development in Angular 5. I'm done with writing HTML code for the UI part. Now I've JavaScript files that provide functionality for the UI elements. As Angular 5 supports typescript for implementing functionality for UI components, I want to include JavaScript files in Angular Project and call them from my Typescript code.

Questions:

  1. How and where to include JavaScript Files in Angular Project?
  2. How to call the JavaScript Functions from Typescript class?

It would be great if anyone provides me an example !!

Thanks in Advance!!

22 days ago ·

Santiago Trujillo

2 answers
Answer question

0

1. How and where to include JavaScript Files in Angular Project?

You need to include your JS file in the asset folder and refer this JS file in .angular-cli.json file.

Refer the snapshot's,

Folder structure should be like this.

enter image description here

.angular-cli.json

enter image description here

2. How to call the JavaScript Functions from Typescript class?

your TS should be like this.

myJsFile.js file content.

enter image description here

This sample logic mentioned above will work, I have tried and tested using version 4, So I am expecting it to work with version 5 also.

Updating the answer for the new Angular version release. Working perfectly till version 11.2.6.

Find the code (function with parameter) here for Angular11

22 days ago · Santiago Trujillo Report

0

The given answer by Arun Raj R is perfect.

But for the angular 6+ project you need to take angular.json instead of angular-cli.json.

also if you want to pass parameter inside external function that come from js file than use just function name.

For Ex :

app.component.ts

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
declare function myfunction: any; // just change here from arun answer.

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
    constructor() { }

    ngOnInit() { 
        myfunction('test1', 'test2');
    }
};

yourJs file :

function myfunction(params1, params2) {
    console.log('param1', params1);
    console.log('param2', params2);
}
22 days ago · Santiago Trujillo Report
Answer question
Remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Startups
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.