Error message: Angular 12 - Event emitter variable is not defined

I'm currently diving into Angular, specifically working with version 12.0.1 and TypeScript 4.3.4. I'm stumped as to why my event emitter is showing up as undefined. Any suggestions or insights?

Here's the error message that keeps popping up: ERROR TypeError: this.gameClick is undefined

.ts file:

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-game-control',
  templateUrl: './game-control.component.html',
  styleUrls: ['./game-control.component.scss']
})
export class GameControlComponent implements OnInit {
  gameInterval: number = 0;
  score: number = 0;

  @Output() gameClick: EventEmitter<any> = new EventEmitter<{ clicks: number }>();

  constructor() { }

  ngOnInit(): void {
  }

  emitEvent() {
    this.gameClick.emit({ clicks: this.score });
    this.score++;
  }

  startGame() {
    this.gameInterval = setInterval(this.emitEvent, 1000);
  }

  stopGame() {
    clearInterval(this.gameInterval);
  }
}

html file:

<div class="controls">
  <button
    class="btn-game"
    (click)="startGame()"
    >Start game</button>
  <button
    class="btn-game"
    (click)="stopGame()"
    >Stop game</button>
</div>

Answer №1

Revise this code:

emitEvent() {
    this.gameClick.emit({ clicks: this.score });
    this.score++;
}

with

emitEvent = (): void => {
    this.gameClick.emit({ clicks: this.score });
    this.score++;
}

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 system encountered difficulty handling a recursive structure

I am facing a challenge with a recursive JSON structure that needs to be stored as a series of maps with keys. The structure comprises flows and subflows that have references to each other. Here are the type declarations, noting that the issue lies in the ...

Using Node.js and Typescript to bring in external modules from

Attempting to generate a random integer between 1 and 6 using the 'random' library. Here's what I have coded so far: import random from 'random' function rollDice(min:number, max:number) { return Math.floor(Math.random() * (ma ...

Retrieving data for a route resolver involves sending HTTP requests, where the outcome of the second request is contingent upon the response from the first request

In my routing module, I have a resolver implemented like this: { path: 'path1', component: FirstComponent, resolve: { allOrders: DataResolver } } Within the resolve function of DataResolver, the following logic exists: re ...

Dealing with name conflicts in Typescript when using multiple interface inheritance

Is it possible to securely implement two interfaces in Typescript that both have a member of the same name? Can this be achieved? For example: interface IFace1 { name: string; } interface IFace2 { name: string; } class SomeClass implements IFace ...

I'm encountering an Unsupported platform error for Angular installation when using [email protected] Does anyone know how to troubleshoot this issue?

C:\Users\vivek>npm install -g @angular/cli C:\Users\vivek\AppData\Roaming\npm\ng -> C:\Users\vivek\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng np ...

Threading in Node.js for Optimized Performance

Having trouble making axios calls in worker threads Hello, I'm working on a Node.js application and attempting to utilize worker threads for one specific task. Within the worker thread, I need to make an axios call, but I keep encountering an error w ...

What is the process for retrieving the parent component from projected content?

One interesting aspect to explore is the varying behaviors of input based on its 'parent' element. The structure I am referring to is as follows: In my first example, the input is nested within the app-chip-list component. APP COMPONENT HTML & ...

Tips on fixing the Angular error: "Argument of type '" | "" | Date' is not compatible with the parameter type 'string | number | boolean."

Currently in Angular-14, I am working on implementing a server-side search filter and pagination. Below is the code snippet that I am using: When fetching data from the web api endpoint, the startDate and endDate values are received as Date format (e.g., ...

Tips for mocking Dependent Modules in Jasmine when dealing with a plethora of dependencies in Angular 9

Looking to create a unit test for a component within an Angular project. The main component has 5-6 dependencies and extends another class with around 7 additional dependencies. What is the most effective method to set up the TestBed for this component? ...

The ng test option is failing to execute effectively

Attempting to conduct unit tests utilizing Karma and Jasmine through the ng test is proving to be a bit challenging. Upon issuing the following command: ng test --watch=false --code-coverage --main ./src/main/resources/public/scripts/xyz/workspace/commons ...

What is the reasoning behind not allowing an empty object as the initial value for hooks?

I am encountering an issue with my setProd Hooks. export interface faceProduct { readonly title: string; readonly prodState: string; readonly shipping: string; readonly sold: string; readonly alt: string; readonly material: string; readonly ...

Customizing Angular 2's Webpack environment setup dynamically

Currently, I have set up Webpack to compile my Angular project. Within my project, there is an important file called env.js: module.exports.ENV = { API_URL: "http://localhost:5001/", ... }; In the webpack.common.js file, I am referencing this file l ...

Creating efficient React components with TypeScript and leveraging generic props

I’ve been working on understanding and resolving my issue with React components' generic props. I came across a code example in an article about using TypeScript with functional React components and generic props. Unfortunately, when trying to repli ...

Struggling to access the html elements within a component once the ng2 page has finished loading?

I am working on a web app that utilizes ng2-smart-table and I want to hide all cells within the table. However, when attempting to retrieve all the cells using document.getElementsByTagName("td") in the ngAfterViewInit() lifecycle hook, I noticed that the ...

Expanding Arrays in TypeScript for a particular type

There is a method to extend arrays for any type: declare global { interface Array<T> { remove(elem: T): Array<T>; } } if (!Array.prototype.remove) { Array.prototype.remove = function<T>(this: T[], elem: T): T[] { return thi ...

Steps for styling the header of an Antd Collapse Panel

I'm attempting to modify the text color in the header of an ant panel. Below is the entire ant collapse component code: <Collapse accordion defaultActiveKey={defaultOpenPanel}> <StyledCollapsePanel key="tasksAssignedToMe" header={ ...

conditionally trigger one observable in rxjs before the other

I am in need of assistance or guidance regarding a challenge I am facing with rxjs that I cannot seem to resolve. In essence, my goal is to trigger an observable and complete it before the original one is triggered. Scenario: I am currently working on a ...

Using the spread operator in React to distribute JSX elements within a map function

I am struggling with mapping over an array within another array to create a Picker and am having difficulty returning JSX elements instead of an array of JSX elements. Here is the code example: {modelA.map((mA) => { const pickerItems = mA.modelB.m ...

How to Make an HTTP POST Request in Angular without Including Headers

How can I configure Angular (version 4.0.2) to send a minimal HTTP POST request? When I use the default code like this: import { Http, Response } from '@angular/http'; export class MyService { constructor(public http: Http) { this.http.pos ...

Navigating json information in Angular 6: Tips and Tricks

I'm currently working on an Angular 6 project and I've encountered an issue with iterating over JSON data fetched using httpClient. If anyone has a solution, I would greatly appreciate the help. The JSON data structure is as follows: Json data ...