Utilize dynamic injection of JavaScript code within Angular 5 for enhanced functionality

For nearly a year now, I've been immersed in a project where we started with Angular 2 during its rc versions, and we've since made our way up to version 5.

One requirement for our app is the ability to transpile TypeScript code into JavaScript and inject it for use.

Here's the scenario: I develop an app with pages, each containing controls that have unique IDs (which we already have in place). I then create a script that adds behaviors to these controls, such as defining actions for user interactions like clicks or changes. If an event is specified in the script for a certain control action, it should be executed accordingly.

Essentially, my app creates a framework with controls and a script file that listens to app events.

In the script, I need to register controls and link events to them, following the typical JavaScript practice.

Additionally, I would include a local API in the script for the app to leverage common functions. A simplified version of the app script is showcased below:

var myPage = myApp.Page("myPageID");
myPage.registerControls('txt1', 'txt2');

myPage.txt1.Events.Click(myClickFunction);

function myClickFunction(sender, event) {
 //Perform actions here
}

When the app is active, the script is injected and is removed upon closure.

Is there a feasible way to accomplish this task?

I have been exploring options similar to JSFiddler, where I can input TypeScript code, transpile it into output JavaScript, export it as a file, and then inject it upon app launch.

Answer №1

Utilizing OpaqueToken allows us to inject a third-party JavaScript library as a service and utilize it within the component.

As an illustration, I am utilizing the "toastr" library to showcase messages. The steps below outline how to achieve this:

1- Add the library reference in the index.html file.

<script src="node_module/toastr/build/toastr.min.js"></script>

2- Create a token to be utilized within the dependency injection registry when registering the global service in AppModule.

toastr.service.ts:

import { OpaqueToken } from '@angular/core';

export let Toastr_TOKEN = new OpaqueToken('toastr');

3- Register in the AppModule.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { ParentComponent } from './parent.component';

import { Toastr_TOKEN } from './toastr.service'

declare let toastr:any; //a globally accessible toastr object

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
  ],
  declarations: [
    AppComponent,
    ParentComponent,
  ],
  providers: [
    { provide: Toastr_TOKEN, useValue: toastr }
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {
}

4- Utilize the toastr object within the component using the @Inject decorator.

import { Component, Inject } from '@angular/core';
import { Toastr_TOKEN } from './toastr.service';

@Component({
  selector: 'parent',
  template: `
    <button class="btn btn-primary" (click)="displayMessage()">Display #</button>

  `
})
export class ParentComponent implements OnInit {
  prime;

  constructor(@Inject(Toastr_TOKEN) private toastr) {

  }

  displayMessage() {
    this.toastr.success('Hello');
  }


}

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

The information in the map cannot be inferred by Typescript based on the generic key type

I encountered a TypeScript issue while refactoring an existing feature in my app. It seems that TypeScript is having trouble picking up the correct type when passing the generic type through nested functions. enum App { AppOne = 'app-one', A ...

Angular 7 compile error NG8002: Unable to bind object as it is not recognized as a valid property

Currently working on an Angular 7/8 test App. Encountering a compile error Can't bind 'discounter' since it isn't a known property of 'paDiscountEditor' The HTML where the error is occurring is simple... Below are all the nec ...

Tips for importing a .geojson document in TypeScript using webpack?

I am trying to extract data from a .geojson file but faced some challenges while attempting two different methods: const geojson = require('../../assets/mygeojson.geojson'); The first method resulted in an error message stating: Module parse f ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

Unexpected error in boot.ts file in Angular 2

I am currently experimenting with various folder arrangements for Angular 2. When attempting to launch a local server, I encounter the following error: Uncaught SyntaxError: Unexpected token < Evaluating http://localhost:3000/prod/app/TypeScript/bo ...

"The debate over using 'stringly typed' functions, having numerous redundant functions, or utilizing TypeScript's string enums continues to divide the programming

I have a specific object structure that contains information about countries and their respective cities: const geo = { europe: { germany: ['berlin', 'hamburg', 'cologne'], france: ['toulouse', ' ...

Storing input values in the state using Typescript by default

Upon launching, my activeField state is initially empty. However, when a user focuses on the field, it gets added to the state. I am encountering a warning in Typescript because when I attempt to update the selectionEnd of that field, it tells me: Property ...

Inkwell shifts bespoke quality

I am currently utilizing Quill (v.2.0.0) with quill-better-table (v.1.2.10) within my Angular 13 project. I am attempting to incorporate a custom attribute to the table tag, as shown below: <table class="quill-better-table" custom-attribute=& ...

Angular - Automatically blur input field in a Reactive Form

I'm encountering a strange problem. Check out the demo .ts import { Component } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'my-app', templateUrl: './a ...

Consecutive requests to APIs using RxJs

Is it possible to efficiently make sequential API calls using RxJs? The challenge lies in the fact that the first Observable emits an array, and for each item in this array, a custom URL should be set for the next call. Additionally, certain conditions nee ...

The installation of msal-angular is encountering issues with the peer rxjs version "^6.0.0" from @azure/[emailprotected]

I am attempting to incorporate @azure/msal-angular for Azure B2C authentication with Angular as the front end, but encountering errors during package installation. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ...

Stretching the Mantine Accordion Section

The Mantine accordion requires that its content be of type Accordion.Item, as indicated in the documentation for the children props. This means that even functions returning AccordionItem will not be recognized. Therefore, only AccordionItem(s) created in ...

Steps for associating ngclass with an observant value

Can you bind to an Observable<enum> like this in Angular? <a [ngClass]="{selected: (mapToolBarMode$ | async) === 0 }" /> or <a [ngClass]="{selected: (mapToolBarMode$ | async) === MapMode.Pan }" /> where the observable is named mapTool ...

Issue encountered when upgrading from Angular 4 to Angular 5: Module '@angular/router' is not found

I recently made the switch from angular 2 to angular 5. However, after the upgrade, I encountered some errors in my ts file. Should I remove @angular/core and @angular/router in angular 5? Here is a snippet of my package.json post-upgrade. Below are the de ...

Simple method for wrestling with objects in TypeScript HTTP POST responses

Can anyone help me understand how to extract information from an object received through an HTTP POST request? Below is the code I am using: this.http.post(url, user, httpOptions).subscribe(result => { console.log(result.status); }); The issue aris ...

Having trouble with the Angular Material component? The element 'mat-option' is not recognized

I am having trouble with implementing an Angular Material component. The component is not functioning properly, and I received the following error message: Uncaught Error: Template parse errors: 'mat-option' is not a known element: // ... I sus ...

Having trouble with React npm start: 'No chokidar version found' error occurring

After cloning my React-Typescript app on Github Pages and attempting to make some changes, I encountered an issue. Despite running npm install to install all dependencies, when I tried to run npm start, I received the following error message: https://i.st ...

Tips for restricting a drag-drop container to only receive a single item in Angular Material's Drag-Drop functionality

Is there a way to restrict the drop container in @angular/cdk/drag-drop module (Angular Material Drag and Drop) to only accept one value instead of multiple values? I am working on a form where users can drag an image and drop it into a field that should o ...

Using Angular to implement conditional logic with ngSwitch

When the number is greater than 5, increase the font size to 50px using ngswitch in case. If the number is less than 2, set the font size to 15px. Unfortunately, I was unable to find a suitable syntax for this scenario, hence no code provided here. ...

What is the best way to connect my Angular 2 project to the "$wakanda" service in order to access and retrieve data efficiently?

Recently, I started a new project on the wakanda.io platform using angular2 and backend technologies. After creating some database entities, I now need to retrieve data from the database on the client side. To do this, I am looking for a way to import the ...