Include an external JavaScript file within a component to display pictures in a web browser using Angular 2

I am developing a website using Angular 2 and need to incorporate a JavaScript file into a component. The goal is for this script to adjust the height of certain images to match the height of the browser window.

What is the best way to integrate this script into the component?

The solutions I have come across on Stack Overflow and other sources suggest importing the script like this:

import './home.component.js';

However, this does not meet my requirements. Ideally, I would like to include it in my home.component.ts file as follows:

@Component({
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss'],
    jsUrls: ['./home.component.js']
})

or something similar...

Update 1: My project utilizes Angular CLI and TypeScript.

Update 2: You can access my project on GitHub: https://github.com/WatchFriends/Web

Answer №1

Here's a great solution that works:

If you're working with the angular-cli.json file, navigate to the "scripts" section and add the path to your script within the array as a double-quoted string.

Take a look at this snippet from the file:


"mobile": false,
"styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.css",
    "../node_modules/font-awesome/css/font-awesome.css",
    "styles.css"
],
"scripts": ["./app/my_script.js"],
"environments": {
    "source": "environments/environment.ts",
    "dev": "environments/environment.ts",
    "prod": "environments/environment.prod.ts"
}

The contents of my_script.js are as follows:


function sayHello() {
   console.log('I am saying hello');
}

After defining the function, you can call it from anywhere without any issues. To avoid the potential "not found" error in your IDE, you have two options: either use window['sayHello'](); or create a utility class containing a reference to the function for seamless invocation (essentially establishing a framework facade for your "my_script.js" functions).

I've personally tested both approaches and encountered no errors while using ng serve or ng build accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are you delving into the realm of reduce functions in order to grasp the intric

Currently following this particular tutorial where they utilize the reduce method to transform an Array<Student> into a { [key: string]: Array<string | number> }. The tutorial includes this expression that caught my attention. It's quite n ...

Creating a mind map: A step-by-step guide

I'm currently developing an algorithm to create a mind map. The key focus is on organizing the nodes intelligently to prevent any overlap and ensure a visually pleasing layout. Take a look at this snapshot (from MindNode) as an example: Any suggestio ...

Display the preloaded element as the first item using Javascript

Is there a way to prioritize the loaded elements using JavaScript? I have an array of elements that I pass to a function and make an AJAX call. While the data is loading, I display a loader (.gif). I want to ensure that the loaded elements are shown first ...

Transferring elements from one array to multiple arrays

I have been working with the basics of JavaScript arrays and here is my code snippet: let arr = ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B&apos ...

.net 6 Attribute routes resulting in a 404 error response

Last week I had a similar question, but now I'm facing an issue with a different controller. I'm baffled as to why I keep getting a 404 error. API Controller... [Route("api/[controller]")] [ApiController] public class FilesController { ...

Angular 4: Implementing toggle switch functionality in Angular 4 by binding boolean values retrieved from the database

Within my application, I am facing an issue with binding a toggle switch to data stored in the database. The data in the database is represented by a field called Status, which can have values of True or False. My goal is to incorporate toggle switch butto ...

Submit information by utilizing' content-type': 'application/x-www-form-urlencoded' and 'key': 'key'

Attempting to send data to the server with a content-type of 'application/xwww-form-urlencode' is resulting in a failure due to the content type being changed to application/json. var headers= { 'content-type': 'applica ...

In JavaScript, capture data returned from a function in a separate variable using a POST REST API call

So, here's the deal - I've got this awesome code that does a POST to an API in order to fetch some data. The best part? It works like a charm when it's wrapped up neatly in a function. But now, the tricky part comes in. I need to actually re ...

There is a compatibility issue between the module and the engine "node" in this instance

Upon running the command npx create-react-app my-awesome-react-app --template typescript, I encountered the following yarn error: Error [email protected]: The engine "node" is incompatible with this module. Expected version "^6 || ^7 || ^8 || ^9 || ^10 || ...

Configure the right-to-left directionality for a particular widget only

Is it possible to align the label inside a TextField component to the right, similar to "labelPlacement" on FormControlLabel? I am aware of using the RTL library with mui-theme, but that applies to the entire application. Is there a way to apply it to jus ...

Having trouble importing Sequelize in Angular?

I'm encountering an issue in my app where I am unable to import the sequelize package. The error message reads: chunk {main} main.js, main.js.map (main) 2.02 kB [initial] [rendered] chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 691 b ...

Error: The "render" method is not available for the IncomingMessage object

While working on a basic application using node.js and express, everything seems to be in order except for this error that keeps popping up: res.render("aggregatedCostList",{ ^ TypeError: Object #<IncomingMessage> has no method 'render&ap ...

Alias route for `src` in Ionic 3

I have set up a custom webpack configuration for Ionic 3 in order to use src as a path alias (meaning I can import from src/module/file): resolve: { alias: { 'src': path.resolve('./src') } } However, after updating to Ionic ap ...

I need help with a process to extract information from a database and convert it into an object specifically for my situation

Currently, I am utilizing the postgres row_to_json function to retrieve data that has been stored using JSON.stringify(). However, upon retrieval and attempting to parse it with JSON.parse(), an error message stating "unexpected token ," is returned. The ...

Incorporate a NodeJS express object into AngularJS 1.6

I am currently facing a challenge with passing parameters from a NodeJS API to AngularJS so that I can retrieve data for a specific page. My situation is an extension of the issue discussed in this question: How do I pass node.js server variables into my a ...

Pressing ctrl and clicking on a link created with the tag element in VueJS will activate

When using a router link without an anchor tag, I am able to ctrl+click the link to open it in a new tab. However, when used with a tag (e.g., tag="td"), the ctrl+click functionality no longer works. The same issue occurs with clickable elements generated ...

Troubleshooting Angular 14 Custom Form Control Display Issue

I'm facing an issue while attempting to develop a custom form control in Angular 14. Despite no errors showing up in the console, my custom control is not rendering as expected. When inspecting the Elements tab in the console, I can see the parent com ...

Exploring Angular's APP_INITIALIZER: Comparing Promises and Observables

I have implemented an Angular v4 application where I need to retrieve settings from the server before the app starts. This is achieved using the APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: initializeSettings, deps: [SettingsService], ...

Embarking on the Mongoose Journey

Every time I enter the code const mongoose = require("mongoose") An error message is displayed: /Users/user/shares3/node_modules/mongodb/lib/utils.js:1069 catch { ^ SyntaxError: Unexpected token { at createScript (vm. ...

I'm having trouble getting my application to output to the console. What could be the issue?

In my cr-route.js file, I have a function that ensures the user is authenticated before displaying their name. module.exports = function (app, passport) { // ===================================== // HOME PAGE (with login links) ======== // == ...