When emitting an event multiple times in Angular, an error may occur where properties of undefined are unable to be read, particularly in relation to the "

I am encountering an issue with my event binding on a button, specifically (click)="onStart()". The problem arises when the event this.numEmitter is emitted for the first time in setInterval, after which I receive the error message

ERROR TypeError: Cannot read properties of undefined (reading 'emit')

    incNum: number;
    timer: number;
    @Output() numEmitter: EventEmitter<number> = new EventEmitter();

    constructor() {
        this.timer = -1;
        this.incNum = 0;
    }

    
    onStart() {
        this.timer = window.setInterval(function () {
            this.incNum++;
            this.numEmitter.emit(this.incNum);
        }, 1000);
    }

    onStop() {
        window.clearInterval(this.timer);
    }

I would greatly appreciate it if someone could help me identify and resolve this issue.

Answer №1

The issue lies in the handler you provided not capturing the correct this. To fix this, consider using an arrow function instead:

onStart() {
  this.timer = window.setInterval(() => {
    this.incNum++;
    this.numEmitter.emit(this.incNum);
  }, 1000);
}

onStop() {
  window.clearInterval(this.timer);
}

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

When running ng new command, an error may occur with dryRunSink.(...).concat not functioning properly

I've been attempting to create a new Angular project by following the steps outlined on this website: https://github.com/angular/angular-cli However, each time I try to initiate a new project using the ng new command, an error occurs. E:\Code&b ...

Facebook sharing woes: Angular app's OG meta tags fail to work properly

Trying to figure out how to properly use og tags for the first time. I'm working on an Angular application and need to share my app link on Facebook with all the necessary tag information included. In my index.html file, I've inserted the follow ...

Sign up for the identical Observable within a Child Component in Angular 2 using TypeScript

This question may seem simple, but as a newcomer to Angular 2, I often find myself needing more explanation despite the good examples and tutorials available. Within a component, I have an observable that gets updated periodically. While I've simplif ...

Angular error: Attempting to create a property on an empty string using Rxjs

Currently, I am working with Angular 11 and using rxjs. I am trying to filter my course collection to show only courses with the category "frontend," but I am encountering some errors. Here is my code: getPosts():Observable<ICourses[]> { return ...

Whenever a file is chosen, I aim to generate the video HTML dynamically and display the video with play functionalities using Angular 2 and TypeScript

I am attempting to allow users to select a video file and display it so they can play it after choosing the file. Below is my HTML code: <br> <input type="file" (change)="fileChangeEvent($event)" placeholder="upload file..." class=" ...

Having trouble retrieving information from a JSON object? Unable to retrieve property 'company_about' of an undefined object?

Here is the JSON data I have: [ { "id": 1, "job_id": 1, "company_profile": "Sales and Marketing", "company_about": "Established in 1992 , it is a renouned marketing company", "company_product": "Ford,Mustang,Beetle", "key_skills": ...

Switching Facebook accounts on Firebase

I'm currently working on an Angular2 App that utilizes Firebase as its User system, with authentication providers including Email + Password, Facebook, and Google. One issue I have encountered is that when logging in with Facebook, I am unable to swi ...

The attribute 'modify, adjust, define' is not found in the 'Observable<{}>' type

After attempting to follow a tutorial on Angular + Firebase, I encountered some issues with version compatibility. The tutorial was based on Angular 4, but my current version is Angular 6. Additionally, the versions of Firebase and AngularFire2 that I am u ...

Alert message will be displayed upon clicking on stepper titles in Angular 10

I need to implement an alert when the user clicks on the second stepper labeled 'Fill out your address'. In addition to displaying a red border around the empty form field, I also want to show an alert message. I have already set up a function ca ...

What is the correct approach to managing Sequelize validation errors effectively?

I am working on a basic REST API using Typescript, Koa, and Sequelize. If the client sends an invalid PUT request with empty fields for "title" or "author", it currently returns a 500 error. I would prefer to respond with a '400 Bad Request' ins ...

How to remove the border of the MUI Select Component in React JS after it has been clicked on

I am struggling to find the proper CSS code to remove the blue border from Select in MUI after clicking on it. Even though I managed to remove the default border, the blue one still persists as shown in this sandbox example (https://codesandbox.io/s/autumn ...

NgRx Action Payload fails to trigger Effect, but no error messages are generated

I've exhausted all resources on Stack Overflow and still can't seem to figure this out. The issue lies in passing a payload into the 'GetUser' action. My intention is for this payload to go through the effect, and eventually be sent v ...

Steps to create a formGroup in Angular 12

import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', ...

Struggling to implement the proper authentication method with API in Ionic

Having an API for the login, but being new to Ionic is causing difficulty in creating the correct method for the login process. The service file is located here: providers/restapi/restapi.ts import { HttpClient } from '@angular/common/http'; im ...

Switch up a button counter

Is there a way to make the like count increment and decrement with the same button click? Currently, the code I have only increments the like count. How can I modify it to also allow for decrements after increments? <button (click)="toggleLike()"> ...

Leveraging Typescript in Firebase Cloud Functions to effectively work with intricate interfaces

When querying a collection on the app side, I am able to automatically cast the result as an interface using Positions constructor that takes in interface IPosition. However, attempting to do the same on the cloud functions side prevents the functions fro ...

Exploring nested static properties within TypeScript class structures

Check out this piece of code: class Hey { static a: string static b: string static c: string static setABC(a: string, b: string, c: string) { this.a = a this.b = b this.c = c return this } } class A { static prop1: Hey static ...

Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own t ...

Does anybody have information on the Namespace 'global.Express' not having the 'Multer' member exported?

While attempting to set up an endpoint to send a zip file, I keep encountering the following error: ERROR in ./apps/api/src/app/ingestion/ingestion.controller.ts:46:35 TS2694: Namespace 'global.Express' has no exported member 'Multer'. ...

Learn how to use Angular 5 to retrieve data from an API

I'm currently working on a data service that fetches data from my API: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { HttpClient, HttpParams } from '@angular/commo ...