What's preventing me from utilizing $event to fetch an array of strings?

When attempting to transfer information from a child to a parent using event emitters and output, an error is encountered:

Argument of type 'Event' is not assignable to parameter of type 'string[]'.
  Type 'Event' is missing the following properties from type 'string[]': length, pop, push, concat, and 29 more.ngtsc(2345)

This is the code snippet from the child component:

@Component({
  selector: 'app-calculator-buttons',
  templateUrl: './buttons.component.html',
  styleUrl: './buttons.component.css'
})
export class ButtonsComponent {
  public firstRow:string[]=['7','8','9','+','='];
  public secondRow:string[]=['4','5','6','*','/'];
  public thirdRow:string[]=['1','2','3','-','AC'];
  public fourthRow:string[]=['0','.','(',')'];
  @Output()
  public onNewResult:EventEmitter<string[]> = new EventEmitter();
  public screenValues:string[]=[];
  
  clear():void{ 
    console.log("Cleared");
    let screen=document.getElementById("screen") as HTMLInputElement;
    screen.value="";
  }
  
  operations():void{
    let screen=document.getElementById("screen") as HTMLInputElement;
    this.screenValues.unshift(screen.value);
    let operation:number=eval(screen.value);
    screen.value=operation.toString();
    this.screenValues[0]+="= "+screen.value;
    this.emitResult();
  }

  monitor(index:string):void{
    let screen=document.getElementById("screen") as HTMLInputElement;
    screen.value+=index;
  }
  
  emitResult():void{
    this.onNewResult.emit({...this.screenValues});
  } 
}

This is the code snippet from the parent component:

import { Component } from '@angular/core';

@Component({
  selector: 'app-main-page',
  templateUrl: './main-page.component.html',
  styleUrl: './main-page.component.css'
})
export class MainPageComponent {

  onNewResult(array:string[]):void{
    console.log("Received Result");
    console.log({array});
  }

}

Here is where the $event is used to receive the event from the child component:

<div class="container bg-secondary rounded my-2 p-2" id="container">
  <calculator-body (onNewResult)="onNewResult($event)"></calculator-body>
  <app-calculator-buttons></app-calculator-buttons>
</div>

Using Angular and Typescript, how can I resolve this error?

I attempted to pass an array of strings from a child component to a parent component by utilizing @Output and EventEmitter. Although the method successfully accesses the child component (as shown in the console), it does not enter the component. The error indicates that $event cannot be assigned to the type array of strings.

Answer №1

The event Emitter was initially set to expect a string, but the emission of an object caused confusion. To address this, I modified the code to emit an array instead of an object.

emitResult(): void {
    this.onNewresult.emit([...this.screenValues]);
}

To resolve the issue, we can update the event onNewResult argument to accept string[].

onNewresult(data: string[]): void {
    console.log(data);
}  

You can find a working example below:

child

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

@Component({
  selector: 'app-calculator',
  standalone: true,
  imports: [FormsModule],
  template: `
    <input type="text" [(ngModel)]="value"/>
    <button (click)="operaciones()">operaciones</button>
  `,
})
export class CalculatorComponent {
  // Component details
}

parent

import { Component, EventEmitter, Output } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { CalculatorComponent } from './calculator/calculator.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [FormsModule, CalculatorComponent],
  template: `
    <app-calculator (onNewresult)="onNewresult($event)"/>
  `,
})
export class App {
  // Parent component details
}

bootstrapApplication(App);

Check out the stackblitz demo here!

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

ngx-graphs -> ngx-graphs-bar-vertical x-axis labels with multiple lines

I'm using 'ngx-charts' with Angular, and I have encountered an issue with long text on my X axis labels. The text overflows and displays three dots instead of wrapping onto multiple lines. Is there a way to make the text wrap onto multiple l ...

Connecting table checkboxes to buttons in Angular 4.x: A step-by-step guide

Exploring Angular 4.x for the first time and faced with a challenge. I have created an HTML table where each row contains a checkbox and buttons. My goal is to link the checkboxes with the buttons in such a way that when a checkbox is checked, the correspo ...

A guide on incorporating typings for d3-tip in TypeScript 2.0

Seeking to implement tooltips in my charts using the d3-tip library. After installing typings for d3-tip in Typescript 2.0: npm install @types/d3-tip --save The typings appear in my package.json: "dependencies": { "@types/d3": "^4.7.0", "@types/d3- ...

Mapped types in Typescript do not allow the addition of extra properties

If I have a type definition like this: A 'Person' must have either the name or fullname property defined. type Person = { [k in "name" | "fullname"]: string; }; If I want to add one more required property, such as age, my ...

What is the best way to create a for loop given this scenario?

Attempting to add pagination in Angular has been a bit challenging for me. While I came across a solution on Google that seemed to work, I'm struggling with properly implementing it. app.component.ts export class AppComponent implements OnInit { or ...

In TypeScript, encountering an unanticipated intersection

In my "models" registry, whenever I select a model and invoke a method on it, TypeScript anticipates an intersection of parameters across all registered models. To demonstrate this issue concisely, I've created a dummy method called "getName". expor ...

The deployment on Vercel for a Node Express and TypeScript project is experiencing issues with building

After uploading my project with node using express + typescript, I encountered a problem. The app generates a folder called dist for building, but when vercel deployed my app, it didn't run the build command. To resolve this issue, I had to manually b ...

What might be causing my observable to fail to return a value?

I'm currently utilizing an API known as ngx-pwa localstorage, which serves as a wrapper for an indexeddb database. Within my Angular project, I have a service that interacts with this database through a method called getItem: getItem(key: string) { ...

Tips for simulating the getCustomRepository function in typeORM

I am facing a challenge in unit-testing a class that has a getCustomRepository method in its constructor. I'm struggling to find an easy way to mock it. Below is the code for my class: import {getCustomRepository} from 'typeorm'; export cl ...

.env file cannot be utilized in JavaScript

Currently, I am working on a project where both the front-end and server are located in one directory. I am using a .env file in the root directory, and the structure of the project looks like this: project frontend (directory) server (directory) .env (fi ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

The element does not recognize the property 'width' since it is not defined in the type of 'GlobalEventHandlers'

I'm trying to determine the size of an image using JavaScript, but I encountered a TypeScript error: const img = new Image(); img.onload = function() { alert(this.width + 'x' + this.height); } img.src = 'http://www.google.com/intl/en_ ...

Creating conditional statements in Angular 2 templates - the power of if, elseif

Can the if elseif else structure be used in an Angular 2 template? Here is an example of using if else: [text]="company ? company.name : 'Select a company'" I am looking to incorporate elseif into this. ...

I am having issues with the Okta Angular sign-in widget as it is not redirecting

Recently, I integrated the Okta angular sign-in widget into my project, but I encountered an issue. In my application, I have multiple modules including an authentication module that manages sign-in, sign-out, and sign-up functionalities. The route I ult ...

Struggling with creating a generic TypeScript structure?

My goal is to manipulate data structured like this: const exampleState = { elements : { element1: { values: { value1: 10, value2: 10, }, elementDetails : { detail1 : { values: { value1: ...

Tips for formatting dates in Angular 6

I am currently working on a function that displays real-time dates based on user input. Currently, when the user enters the input, it is displayed in the front end as follows: 28.10.2018 10:09 However, I would like the date to change dynamically based on ...

Leveraging services in Angular: accessing directly in view or via component

I am currently working on an application that consists of multiple pages, each with their own components. I have a single config.service.ts file where the debug mode is set as a boolean. Within my views, depending on this setting, I need to show buttons, ...

Sluggish website loading time

Hey there, I'm currently developing a website and I'm facing a major issue with one of my pages loading slowly and experiencing lag. I'm unsure if this is due to the on scroll listeners or the excessive references in my code. Could it possib ...

Set a parameter for my AppComponent during the Bootstrap process

Currently, I am working on an Angular version 7 app that is being hosted within an ASP.NET application. My goal is to have a dropdown in the .NET app and use the selected value to call the Angular app. I've made numerous attempts to pass a parameter d ...

Unleashing the power of TypeScript in combination with svelte and d3

Currently, I am facing an issue with TypeScript regarding data types. Specifically, I am working on a Svelte component for the x-axis of a d3 visualization. In this component, I receive the xScale as a property from the parent component like this: <XAix ...