Calling JavaScript Functions from TypeScript in Angular 5: A Comprehensive Guide to Integrating External Scripts

Dec 04, 2025 · Programming · 10 views · 7.8

Keywords: Angular | TypeScript | JavaScript Integration

Abstract: This article provides an in-depth exploration of integrating external JavaScript files into an Angular 5 project and calling their functions from TypeScript code. By analyzing best practices, it first explains how to correctly place JS files in the assets folder and reference them in the .angular-cli.json configuration file. Then, it delves into the technical details of declaring global functions using declare in TypeScript classes and directly invoking them, including parameter passing and error handling. The article also discusses the fundamental differences between HTML tags like <br> and characters to ensure clarity in code examples. Finally, it offers compatibility advice and practical code samples for Angular 11 and earlier versions, aiding developers in efficiently implementing UI features such as PDF viewers.

Introduction

In modern web development, the Angular framework widely adopts TypeScript as the primary programming language to provide type safety and better tooling support. However, in real-world projects, developers often need to integrate existing JavaScript libraries or scripts, such as in PDF viewer development where UI functionality may be provided by external JS files. This article addresses a common issue: how to include JavaScript files in an Angular 5 project and call their functions from TypeScript classes. By analyzing the best answer and supplementary references, it offers a complete solution. We will start with project structure configuration and gradually move to code implementation, ensuring the content is both comprehensive and easy to understand.

Including JavaScript Files in an Angular Project

To integrate external JavaScript files into an Angular project, it is essential to correctly place the files and configure the build tool. Based on best practices, it is recommended to place JS files in the src/assets folder. This folder is designated for static resources such as images, fonts, and scripts, which are copied to the output directory during the build process. For example, assuming we have a file named myJsFile.js containing UI functionality functions, we can place it in a subdirectory like src/assets/js to maintain organization.

Next, this JS file must be referenced in the project configuration file .angular-cli.json. In Angular 5, this file manages project settings, including the loading of scripts and styles. Add the path to the JS file in the scripts array, ensuring the path is relative to the project root. For example: "scripts": ["src/assets/js/myJsFile.js"]. This way, when the application starts, the Angular CLI automatically includes this script in the generated HTML, making it available globally. It is important to avoid using <script> tags directly in HTML files, as this may cause loading order issues or conflicts with Angular's module system.

Calling JavaScript Functions from TypeScript Classes

Once the JavaScript file is correctly included, its functions can be called from TypeScript code. Since TypeScript is a superset of JavaScript, it can interact directly with JS, but for type safety and to avoid runtime errors, it is advisable to use type declarations. First, in the TypeScript file, use the declare keyword to declare global functions. This informs the TypeScript compiler that these functions exist in the global scope without needing module imports. For example, if myJsFile.js defines a function showPDF(), you can add in a TypeScript class: declare function showPDF(): void;.

Then, call this function directly in TypeScript methods, just like a local function. For instance, in an Angular component, you can call it in the ngOnInit lifecycle hook: showPDF();. If the function requires parameters, simply specify the types in the declaration and pass values during the call. For example, for a function loadPDF(url: string), declare it as declare function loadPDF(url: string): void;, then call loadPDF("https://example.com/document.pdf");. This ensures type checking while maintaining the flexibility of JS.

To handle potential errors, it is recommended to add error handling mechanisms. For example, use try-catch blocks to catch exceptions during the call and log them or display user-friendly messages. Additionally, considering cross-version compatibility, this method has been tested and proven effective from Angular 4 to version 11.2.6. In Angular 11, the configuration file has changed to angular.json, but the principle remains the same: reference the JS file path in the scripts array.

Code Examples and In-Depth Analysis

Let's solidify these concepts with a concrete example. Suppose we are developing a PDF viewer where myJsFile.js contains the following function: function displayPDF(fileName) { console.log("Displaying PDF: " + fileName); }. In the Angular project, first place the file in src/assets/js and configure it in .angular-cli.json. Then, in the TypeScript component file:

declare function displayPDF(fileName: string): void;

@Component({
  selector: 'app-pdf-viewer',
  templateUrl: './pdf-viewer.component.html',
  styleUrls: ['./pdf-viewer.component.css']
})
export class PdfViewerComponent implements OnInit {
  ngOnInit() {
    displayPDF("sample.pdf");
  }
}

This example demonstrates seamless integration of JS and TypeScript. Note that in HTML, tags like <br> are used for line breaks, but in code descriptions, we discuss their nature as text objects, so they should be escaped as &lt;br&gt; to avoid parsing errors. For instance, when explaining strings: print("<T>") should have <T> escaped to &lt;T&gt; to ensure correct output.

Compatibility and Best Practices

The method described in this article is effective in Angular 5 and has been extended to Angular 11.2.6. For newer versions, such as Angular 12 and above, the configuration files may differ, but the core concepts remain: include JS files as resources and call functions via global declarations. It is advisable to always test cross-version compatibility and refer to official documentation for updates. Additionally, consider using module bundlers like Webpack to optimize script loading, though this is beyond the scope of this article. In summary, by following these steps, developers can efficiently leverage existing JavaScript code in Angular projects, enhancing development efficiency and maintaining code quality.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.