当我try 使用事件发送器和输出从子对象向父对象传递信息时,收到以下错误:

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)

这是子代码

@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[]=[];
  apagar():void{ 
    console.log("Apagado");
    let pantalla=document.getElementById("pantalla") as HTMLInputElement;
    pantalla.value="";
 
}
 operaciones():void{
  let pantalla=document.getElementById("pantalla") as HTMLInputElement;
  this.screenValues.unshift(pantalla.value);//añado el valor de la operacion al princio del array 
  let operacion:number=eval(pantalla.value);//eval trasfoma una cadena en una operacion matematica
  pantalla.value=operacion.toString();
  this.screenValues[0]+="= "+pantalla.value;
  this.emitResult();
  //usar services para pasar datos desde buttons hasta screen

}

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

这是父代码:

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



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

 onNewResult(arreglo:string[]):void{
  console.log("Resultado recibido");
  console.log({arreglo});
 }

}

在这里我使用$event来获取子事件

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

我正在使用Angular和Typescript,我可以做些什么来删除这个错误?

为此,我try 将字符串数组从子组件传递到父组件,我使用@Output和EventEmmiter,该方法设法访问子组件(消息出现在控制台中),但它从未进入组件,错误似乎是$Event不可分配给字符串数组类型

推荐答案

您已将事件emits 器设置为字符串,但您正在emits 一个令人困惑的对象.因此,我将代码转换为发出数组,而不是对象.

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

我们可以将事件onNewResult参数更改为string[],这将解决问题!

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

下面是工作示例.

children

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 {
  value = '';
  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<string[]>();
  public screenValues: string[] = [];
  apagar(): void {
    console.log('Apagado');
    this.value = '';
  }
  operaciones(): void {
    let pantallaValue = this.value;
    this.screenValues.unshift(pantallaValue); //añado el valor de la operacion al princio del array
    let operacion: number = eval(pantallaValue); //eval trasfoma una cadena en una operacion matematica
    pantallaValue = operacion.toString();
    this.screenValues[0] += '= ' + pantallaValue;
    this.emitResult();
    //usar services para pasar datos desde buttons hasta screen
  }

  monitor(index: string): void {
    let pantalla = document.getElementById('pantalla') as HTMLInputElement;
    pantalla.value += index;
  }
  emitResult(): void {
    this.onNewresult.emit([...this.screenValues]);
  }
}

亲本

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 {
  onNewresult(data: string[]) {
    console.log(data);
  }
}

bootstrapApplication(App);

stackblitz

Typescript相关问答推荐

TypScript中的算法运算式

具有映射返回类型的通用设置实用程序

等待的R没有用响应对象展开到R

TypScript手册中的never[]参数类型是什么意思?

我用相同的Redux—Toolkit查询同时呈现两个不同的组件,但使用不同的参数

接口的额外属性作为同一接口的方法的参数类型'

单击并移除for循环中的一项也会影响另一项

如何键入函数以只接受映射到其他一些特定类型的参数类型?

对于合并对象中的可选属性(例如选项),类型推断可能是错误的

Material UI / MUI系统:我如何告诉TypeScript主题是由提供程序传递的?

函数重载中的不正确TS建议

AngularJS服务不会解析传入的Json响应到管道中的模型

在打印脚本中使用泛型扩展抽象类

转换器不需要的类型交集

TYPE FOR ARRAY,其中每个泛型元素是单独的键类型对,然后在该数组上循环

为什么TS2339;TS2339;TS2339:类型A上不存在属性a?

使用&reaction测试库&如何使用提供程序包装我的所有测试组件

如何在TypeScript中将元组与泛型一起使用?

TS 条件类型无法识别条件参数

解析错误:DeprecationError: 'originalKeywordKind' 自 v5.0.0 起已被弃用,无法再使用