不能使用除 $event 之外的任何其他变量名来接收 Angular 中发出的数字

Can't use any other variable name than $event for reception of the emitted number in Angular

注意。问题不是 如何 让它工作(因为我可以,如底部所述)。更重要的是 为什么 我可以让它以这种方式工作而不是其他方式。

我设计了这样一个组件。它是一个数据行,可以保留一堆 och 数据行。因此,在每个这样的实例中,我们都有 onRemoval(当用户点击删除图标时调用)以及 onRemove(当发出甚至被听到)。

@Output() remove: EventEmitter<number> = new EventEmitter<number>();
...
onRemoval() {
  console.log("being removed: " + this.id);
  this.remove.emit(this.id);
}
onRemove(id: number) {
  console.log("removing: " + id);
  if (!id)
    return;

  this.subRows.splice(id, 1);
}

我确定我遗漏了一些愚蠢的东西,但是当我尝试调试它时让我感到困惑的是发出的值是正确的索引,而接收到的值不是。它是 未定义

我尝试过的标记的相关部分如下所示。我也试过空括号,也没有括号。

<div *ngIf="unfolded">
  <app-data-row *ngFor="let subRow of subRows"
                (remove)="onRemove(id)"
                [config]="subRow"></app-data-row>
</div>

我用谷歌搜索了这个,但据我所知,我遵循了使用 EventEmitter 的正确方法。此外,似乎设置在发出和接收事件时有效。只是id值好像没有设置好

让它工作的唯一方法是调用变量 precisely $event 而不是别的。那是我在做一些愚蠢的事情还是这是必需的语法?!我的意思是,甚至 *$id$ 都没有帮助...

在模板中,当将子项的输出连接到组件的回调时:$event 是发出的值的名称,没有办法绕过它。毕竟:调用处理程序不需要 将输出作为其唯一参数。你可以做,不知道,

<app-data-row *ngFor="let subRow of subRows" (remove)="onRemove(subRow.id)">

<app-data-row *ngFor="let subRow of subRows" (remove)="onRemove(subRow.id, $event)">

<app-data-row *ngFor="let subRow of subRows" (remove)="onRemove($event, subRow.id)">

等等,等等。所以,这里模板中需要$event作为实际输出值的标识。

$event 是事件本身,当使用 component/directive 的 @Output 事件发射器时,它会发出值,并由带有 $event 变量的回调函数捕获。

当你用括号定义事件侦听器时,例如

(remove)="onRemove($event)"

你实际上传递了一个方法引用。您不需要之前定义的局部变量。 Angular 本身用发出的值替换 $event 值。但是如果你这样做

(remove)="onRemove(id)"

它认为 id 是您在 *ngFor="let id of idList"

中定义的局部变量

简而言之,这是使用 component/directive 的输出事件发射器时捕获发射值的唯一方法。

你可以看看这个官方文档:https://angular.io/guide/user-input

还有这个 SO 线程: