Unable to access class instance from event handler in Angular 2 and Typescript

In the scenario I'm working on, I need to dynamically add multiple instances of a child component to a template. Each of these child components emits a 'select' event, and each one requires a different event handler within the parent component. To handle this, I decided to store the event handler as a property of each item in an array called 'componentArray'. As a result, my template now looks like this:

<my-cmp *ngFor="let childComponent of componentArray" (select)="childComponent.callback()"></my-cmp>

My model is structured as follows:

componentArray = [{data:0, callback:this.onSelect0}, {data:1, callback:this.onSelect1}];

onSelect0(){/*do stuff specific to childComponent 0*/}
onSelect1(){/*do stuff specific to childComponent 1*/}

The 'callback' property holds a reference to the specific method I want that particular child component's 'select' event to trigger. While the 'callback' function is being triggered correctly, the issue arises when trying to access other components within the parent component. The context of 'this' within the callback refers to the 'component' during that specific iteration of the loop.

Although I found a workaround by storing the class instance as a property in each item of 'componentArray', it feels cumbersome. I have a Plunkr demo available at http://plnkr.co/edit/VxxCR8hjUsxQ3SABWe8E?p=preview to illustrate my issue. Essentially, my question is: if I pass the event handler as an object property ('childComponent.callback' in the example above), how can I access my class instance? Any insights or suggestions would be appreciated.

Answer №1

By default, in JS/TS, if you pass a method reference directly, it will behave a certain way. To maintain the scope of 'this', you can either use the bind method like methodName.bind(this) or a fat arrow function like () => methodName().

Make the following change in your Plunker:

  private thing = {name:'ThingOne', onSelect:() => this.handlerOne() };

Check out this Plunker example for reference.

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

Having trouble getting Chrome to load my JavaScript script file

Setting up a server on my computer was a simple task, but now I am facing an issue with loading a script file in my HTML. var express=require('express'); var app=express(); app.listen(3000); app.use(express.static('/scripts' ...

Event-Propagation in Angular 5 with mat-expansion-panel within another component

In my project, I am facing a challenge where I need to create multiple mat-expansion-panels within one mat-expansion-panel. Everything works fine except for the issue that when I try to open a child-panel, it triggers the close-event of the parent-panel. ...

Using the jQuery dialog to load a URL with a datetime picker integrated into

I recently created two pages. One page contains a link that opens a dialog and loads another page inside that dialog. However, when I click on the calendar on the loaded page, I receive the error message: "Cannot read property 'inline' of undefin ...

The v-on:click functionality seems to have become unresponsive after being dynamically added through modifying the inner

While attempting to create a dynamic navbar, I encountered an issue. The goal was to have the navbar switch from displaying "login" and "register" when a session is logged in, to showing "profile" and "logout". The buttons for login and register were fun ...

The key to creating efficient routers in Express: Don't Repeat Yourself!

Currently, I am in the process of developing a web application in the form of a network structure that involves basic CRUD operations. However, I am facing the issue of having overly large router files, prompting me to consider splitting them up. One of t ...

Moving the login page to a different server in Django without the CSRF token

I have a login page that utilizes the django authentication system. Now, I am looking to transfer just the login page to a separate server (an external login page). My goal is to have the username and password fields on the external login page, and then ...

The ref.on() method fails to trigger a response from a function, despite producing the intended outcome

I've been working on developing an app called workspace. I previously asked a question, but I've made more additions to the features now. One of the new features is a remarks system. After experimenting with different versions of my code, the ver ...

The HTML5 camera feature remains active even after navigating to a different page in an AngularJS application

I am currently exploring the video capabilities of HTML5. Using a directive userMedia, I have successfully activated my camera on my MacBook through navigator.getUserMedia() (using an adapter for cross-browser compatibility with supported browsers). Howev ...

Error handling middleware delivering a response promptly

Issue with my express application: Even after reaching the error middleware, the second middleware function is still being executed after res.json. As per the documentation: The response object (res) methods mentioned below can send a response to the cl ...

Error message: Unable to access the state property of an undefined object

I've been attempting to integrate a react sticky header into my stepper component. However, I've encountered an issue where it doesn't render when added inside my App.js file. As a result, I've started debugging the code within App.js ...

A method for determining the quantity of <li> elements within a <ul> container while applying specific conditions

I am currently using document.querySelectorAll('ul > li').length to count the total number of items in my list. However, I am wondering if there is a way to count only those items that meet a specific condition. For example: <ul> < ...

The console errors in the test are being triggered by the Angular setTimeout() call within the component, despite the test still passing successfully

I am currently experimenting with a click action in Angular 7 using an anchor tag Below is the markup for the anchor tag in my component <div id="region-start" class="timeline-region"> <div class="row"> <div class="col-12 col-md- ...

What is the method to ensure that the Node REPL solely displays the result?

Is there a way to execute a script in Electron that only logs the output value without displaying all the code? I am utilizing xterm.js and node-pty for this project. For instance, consider the following sample code: // Add your code here function multi ...

What could be causing my CSS and Bootstrap.css styles not to be implemented on my webpage?

While working on my Ruby on Rails application, I am trying to customize the design to resemble (which can be downloaded from ). However, I am facing an issue where the style sheets are not being applied. I have moved the style sheets from the bootstrap/c ...

@angular/common@~5.1.1 is needed as a peer dependency for @angular/[email protected], however it is not currently installed

There seems to be a peer dependency issue with @angular/common@~5.1.1 while trying to install the angular date picker from NPM console. Upon running the command npm install angular2-material-datepicker, I encounter the above error message. npm install ...

Transforming ajax code into node.js

After mastering ajax calls for client-server interaction, I am facing a challenge in converting my code to a server-side node compatible JS using http requests. Despite reading various tutorials, I am struggling to adapt them to fit with my current code st ...

Encountering Axios CanceledError while attempting to forward a POST request using Axios

While attempting to relay a POST request from an express backend to another backend using axios, I encountered an axios error stating "CanceledError: Request stream has been aborted". Interestingly, this issue does not arise when dealing with GET requests. ...

What is the reason for the error that Express-handlebars is showing, stating that the engine

I recently added express-handlebars to my project and attempted the following setup: const express = require("express"); const exphbs = require('express-handlebars'); const app = express(); app.engine('.hbs', engine({defaultL ...

Changing of expression is detected upon entering but not when clicking

I encountered an issue in my Angular 7 application where pressing the enter key in an input field triggers an error, while clicking on the search button does not: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. ...

Submitting modal form information using AJAX to PHP

As a novice in the realm of web programming, I find myself seeking some guidance to untangle a riddle. Regrettably, my grasp of the basics still leaves much to be desired. Within my main page, view.adminsettings.php, I've designated a Navigation DIV ...