Exploring window event handling in Typescript (angular2)

Trying to capture events on the window object from an Angular 2 application written in TypeScript. Additionally, jQuery (imported via typings) is being used.

The desired events are generated by an external library included using <script> tags in index.html. When a listener is added to window in index.html, everything works as expected:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="http://my-host/front-libs/jquery/1.8.3/jquery-1.8.3.min.js"></script>
    <script src="https://my-host/my-external-lib.min.js"></script>
    <title>Angular 2 App | ng2-webpack</title>
    <link rel="icon" type="image/x-icon" href="/img/favicon.ico">
    <script>
      // this works!!
      $(window).on('authenticatedUser', function(e) {
        console.log('ok.');
      });
    </script>
    <base href="/">
  </head>
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

However, attempting to listen for the same events within the Angular2 app does not yield the desired outcome:

import { Component, OnInit } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

import { ApiService } from './shared';

import '../style/app.scss';


/*
 * App Component
 * Top Level Component
 */
@Component({
  selector: 'my-app', // <my-app></my-app>
  providers: [ApiService],
  directives: [...ROUTER_DIRECTIVES],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
  url = 'https://github.com/preboot/angular2-webpack';

  ngOnInit(){


   // This method doesn't seem effective. Notifications for 
   // 'authenticatedUser' events on `window` are never received
   $((<any>window)).on('authenticatedUser', function(e) {
     console.log('fuuuu');
   });


   // This successfully triggers events on `window`
   (<any>window).myNamespace.start({
      scopeName: null,
      canClose: false,
      returnUrl: 'http://localhost:8080/loggedIn'
    });
  }

  constructor(private api: ApiService) { }
}

Is this the proper approach for attaching event handlers to the window object from within an Angular 2 app? There might be a more efficient way to accomplish this task.

Answer №1

Is this the proper way to bind event listeners to the window from an Angular 2 application?

If it works in JavaScript, it should work in TypeScript as well. The method I'm about to demonstrate will not solve that issue.

However, it is not recommended to handle window events like that in Angular. Instead, Angular suggests something along the lines of:

host: {
    '(window:resize)': 'onResize($event)'
}

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

Utilizing Ajax Requests in Liferay 6 Portlets

I am looking to implement an AJAX call within my JSP file that will invoke the processAction method of a portlet. Depending on the success message returned by the processAction method, I then need to initiate another call to the serveResource method of t ...

Generating varying commitments from one function

I have encountered an issue where I am returning a promise from a function that is part of a $q.all array. Initially, this setup works perfectly on page load. However, the challenge arises when I need to call this function multiple times afterward to updat ...

JavaScript button click changes the selected row's color in a DataTable

I am looking to dynamically change the color of a row in my Datatable when a specific button is clicked. Here is the HTML code snippet for the rows: <tr role="row" class="odd"></tr> <tr role="row" class="even selected"></tr> & ...

Use the button to trigger the opening of the datepicker in React material UI

Currently, I am incorporating a Datepicker in my project using React Material UI. <TextField id="datetime-local" label="Next appointment" type="datetime-local" defaultValue="2017-05-24T ...

Retrieve an array from the success function of a jQuery AJAX call

After successfully reading an rss file using the jQuery ajax function, I created the array function mycarousel_itemList in which I stored items by pushing them. However, when I tried to use this array in another function that I had created, I encountered t ...

Troubleshooting: ReactJS image change on mouse over not functioning

My objective is to develop a stateless image button component that changes images upon hovering, which can be easily reused in various other instances. However, I'm currently facing an issue where I'm unable to set the "hover" image when the onM ...

Guide on implementing an onClick event for rows in an Angular Mat-Table and navigating to a separate page

I'm seeking guidance on how to implement a click event for a specific row that will navigate to the next form while carrying over the values of the clicked row. I find this concept a bit perplexing at the moment. <!-- Position C ...

What is the reason for this error message: The 'filter' property is not found on type 'Films'?

Could use some help with PrimeNG integration in my app as I've encountered a persistent error. I'm aiming to implement a delete function using confirmationDialog. Below is the excerpt from my component.ts file: export interface Films { id?: a ...

Having trouble with your Bootstrap modal not opening automatically when the page loads?

I have a modal that is successfully opening with a button: <button onclick="content()" data-toggle="modal" data-target="#my_modal">Save</button> <form action="addPage.php" method="post"> <div class="modal fade" id="my_modal" tabind ...

*ngFor fails to update existing table rows and instead just appends new rows

In my project using Sonic 3, I am utilizing the SQLite plugin to insert data into a SQLite database. Subsequently, I retrieve this data and display it in my template. This is the TypeScript file: saveData() { this.sqlite.create({ name: 'i ...

How to retrieve the output of a nested function in Node.js

I have been attempting to retrieve a value from a function nested inside another function in my Node.js application, but it always seems to return undefined. var geo = { list: function(callback){ var returnval; gapi.getcodes(function(e ...

Creating a custom name for a specific node_module

Previously, we had a folder containing various typescript modules. However, we have now transformed that folder into a package. An issue arises with the existing code, as it uses webpack aliases for that particular folder. I am attempting to have those al ...

Do we require 'function()' when declaring an event?

I currently have two scripts included in my project: <script src="../js/createopp.min.js"></script> <script src="../js/validation.min.js"></script> Within the first script, there is a line calling a function from the second script ...

Techniques for implementing a PHP base_url() function in a JavaScript file

I need to pass base_url from the Book Controller to the book.js file This is the function within book.js function loadPage(page, pageElement) { // Create an image element var img = $('<img />'); img.mousedown(function(e) { ...

Tips for invoking a function in an ASP.NET code-behind file using JavaScript

I'm currently trying to display an image in my div by calling a function from the code behind file. The image tag is dynamically bound with JavaScript, but I'm having trouble figuring out how to call a function with parameters. The code snippet I ...

Jquery ajax request unsuccessful due to missing error message

An issue arises with the ajax request below as it fails to display an error message: $.ajax({ type: "POST", url: loginUrl, data: JSON.stringify({login : u, password : p}), contentType: "application/json; charset=utf-8", success: functi ...

Filtering JSON data using jQuery

Is there a way to narrow down a Google Spreadsheet JSON (like the one found here: ) so that I only receive the json-entry where the field contains "title":{"type":"text","$t":"test1"} or in other words, "where title = test1". All I am looking for from the ...

Unable to access member function of Typescript class

I recently started using typescript and encountered an issue while working on a problem. I initially created the following class: export class ModuleInfoContainer extends Array<ModuleInfo> { constructor() { super(); } search(id: number) { ...

Using raycasting in Three.js to select objects and adding animation

In my current project, I have found that raycasting selection works perfectly fine for static meshes. However, when it comes to animated meshes, I have encountered an issue where the ray selection does not take into account the movement of the mesh. Instea ...