Enhancing Angular 5 with CustomEvent Polyfill for JavaScript

After implementing the code snippet in main.ts file, I encountered an issue with CustomEvent not being added to the window object correctly. Strangely, when I manually add CustomEvent using the JavaScript console, it works fine. This problem arises specifically when I click on a button that triggers the custom event named "choice-click".

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

function CustomEvent ( event, params ) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
}

CustomEvent.prototype = (<any>window).Event.prototype;

(<any>window).CustomEvent = CustomEvent;

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

Provided below are two screenshots. The first one shows how CustomEvent is being added in main.ts, whereas the second image depicts the manual addition of CustomEvent using the JavaScript console.

Note: When using the $.isFunction in the JavaScript console, it returns "true"

https://i.sstatic.net/Bt6Ni.png

https://i.sstatic.net/g4qwP.png

Answer №1

In case you are utilizing Angular CLI, there is an option to incorporate the "custom event polyfill" by executing the command npm i custom-event-polyfill and integrating it into your polyfills.ts file like this: import 'custom-event-polyfill';

Answer №2

I wasn't sure where to place the polyfill - before or after Angular - but it seems to be working fine.

<script type="text/javascript" src="inline.bundle.js"></script><script type="text/javascript" src="polyfills.bundle.js"></script><script type="text/javascript" src="styles.bundle.js"></script><script type="text/javascript" src="scripts.bundle.js"></script><script type="text/javascript" src="vendor.bundle.js"></script><script type="text/javascript" src="main.bundle.js"></script>
<script type="text/javascript">
    function CustomEvent ( event, params ) {
        params = params || { bubbles: false, cancelable: false, detail: undefined };
        var evt = document.createEvent( 'CustomEvent' );
        evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
        return evt;
    }

    CustomEvent.prototype = window.Event.prototype;

    window.CustomEvent = CustomEvent;
</script>

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

Integrating Vimeo videos into Angular applications

I am attempting to stream videos using URLs in my Angular application. Every time I try, I encounter the following error: Access to XMLHttpRequest at 'https://player.vimeo.com/video/548582212?badge=0&amp;autopause=0&amp;player_id=0&amp;ap ...

Create a new tab that is active and use ng-repeat in the uib-tab directive

I've been trying to solve this problem for a while now. I came across a similar post, but it was left unanswered. So, I decided to create my own post with a Plunkr example. The issue I'm facing is that upon loading, the ui-tab always defaults to ...

Displaying a sub-menu for specific menu options to fetch content using routes in ReactJS

Currently, I am in the process of learning the React JavaScript library. My goal is to develop a basic web application that consists of a menu, submenu, and content sections. For this project, I am using react 15.0.2, react-router 2.4.0, babel 6.5.2, and w ...

Unable to transfer the form value to the service and City value cannot be updated

I am new to the world of Angular and I am attempting to create a basic weather application. However, I am encountering issues when trying to pass the city value from the form on ngSubmit to the API service. I have attempted to use an Emitter Event to trans ...

When new text is added to Div, the first line is not displayed

One of the divs on my page has an ID of "TrancriptBox" and contains multiple lines of text. When I scroll through it on my iPad, everything works fine. However, if I scroll and then change the text within that div, it doesn't display the first line o ...

Tips for using an ArrayBuffer to stream media in Angular

Currently, I am facing an issue while transferring data from my backend with nodeJS to Angular. Everything seems to be working fine except for one problem - my media files are not functioning properly in my code. To resolve this, I have implemented Blob fi ...

Error in JavaScript goes undetected when utilizing asynchronous AJAX

Having recently started working with ajax and javascript, I find myself puzzled by the fact that my error is not getting caught when making an asynchronous ajax call. I did some research on a similar issue in this query (Catch statement does not catch thr ...

Converting JSON to TypeScript: How to properly serialize property names instead of the base class field names

Take a look at the code snippet below. I anticipate the serialized result to be: { "origin": { "x": 1, "y": 2 }, "size": { "width": 3, "height": 4 } } However, the actual result is: { "origin": { ...

Utilize PHP's file_get_contents to trigger the Google Analytics tracking pixel

For certain goals I have set up in Google Analytics, I am unable to use the JavaScript tracking. Instead, I am interested in achieving the same result by making a call with PHP. One solution that seems straightforward to me is to invoke the URL of the tra ...

How can I fix my HTML Image input not redirecting when clicked?

I have successfully implemented the following code: <input type="button" name="btnHello" value="Hello" onclick="Test();"/> Here is the JS function that accompanies it: function Test() { window.location.href = "Page2.aspx"; } Initially, clicking ...

"Learn the trick to concealing a modal and unveiling a different one with the power of jquery

Whenever I try to open a modal, then click on a div within the modal in order to close it and open another one, I encounter an issue. The problem is that upon closing the first modal and attempting to display the second one, only the background of the seco ...

The dynamic route parameter does not currently have compatibility with languages that utilize Unicode characters apart from the English

NextJS 13 (beta) Official Documentation provides information on dynamic route parameters in this link. Clarification: app/shop/[slug]/page.js To retrieve the slug, use params.slug. Example: app/shop/this-is-shop/page.js In this case, params.slug will o ...

Positioning Data Labels Outside of Pie or Doughnut Charts in Chart.js

I am currently working on a large-scale project and I am in need of a way to position the labels outside of pie charts or doughnut charts. I came across a plugin called outerLabels on GitHub which seems to be the perfect solution for what I need, but I am ...

What is the method to retrieve the index or row number using the map function in Google Sheets?

Currently, I am attempting to retrieve the row number where the row meets certain criteria. However, I seem to be encountering an issue: Instead of getting the desired result, I am obtaining an array like this: [,,2] Although I have attempted using filter ...

Change the background color of mat-select to match the selected mat-option

<mat-form-field> <mat-select [formControlName]="name"> <mat-option [value]="option.id" [ngStyle]="{backgroundColor: option.color}" *ngFor="let option of list; let i = index" ...

Mastering Vue 3: Simplifying a reactive array of objects while maintaining reactivity

Struggling with maintaining reactivity in Vue 3 when flattening a nested array of objects. Unfortunately, my attempts result in crashing and browser hang-ups. In my Vue 3 component, I have an array structured as a list of objects: this.grouped = [ ...

Searching for a way to access the HTTP request header using ReactJS?

Can anyone assist me in retrieving the request header's cookie? I have searched extensively but haven't found a satisfactory document. Please share with me a reliable solution. ...

Is it possible to execute JavaScript code (using Node.js) through AppleScript on MAC OS?

After downloading Node.js for MAC OS from this link: http://nodejs.org/download/ (http://nodejs.org/dist/v0.10.29/node-v0.10.29.pkg), I needed to execute a JavaScript on Google Chrome. To do this, I utilized the following AppleScript code: do shell script ...

Comparing dates in Angular 6 can be done by using a simple

Just starting with angular 6, I have a task of comparing two date inputs and finding the greatest one. input 1 : 2018-12-29T00:00:00 input 2 : Mon Dec 31 2018 00:00:00 GMT+0530 (India Standard Time) The input 1 is retrieved from MSSQL database and the in ...

React - Uncaught Error: e.preventDefault is not a function due to Type Error

Encountering an issue with Axios post and react-hook-form: Unhandled Rejection (TypeError): e.preventDefault is not a function The error arises after adding onSubmit={handleSubmit(handleSubmitAxios)} to my <form>. Seeking to utilize react-hook-form ...