考虑以下代码(从这里):
父组件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `<app-child (valueChange)='displayCounter($event)'></app-child>`
})
export class AppComponent implements OnInit {
ngOnInit() {
}
displayCounter(count) {
console.log(count);
}
}
子组件:
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: `<button class='btn btn-primary' (click)="valueChanged()">Click me</button> `
})
export class AppChildComponent {
@Output() valueChange = new EventEmitter();
Counter = 0;
valueChanged() { // You can give any function name
this.counter = this.counter + 1;
this.valueChange.emit(this.counter);
}
}
正如您在父组件中看到的那样,我们使用displayCounter($event)
来接收从子组件发出的数据。
我的问题是为什么我们必须为此使用$event
关键字?
如果我尝试将displayCounter($event)
更改为displayCounter(count)
则不起作用。 但是,我可以将方法的名称从displayCounter
更改为myAwesomeDisplayCounter
。 通常javascript中的函数没有设置参数名称,所以我对为什么在Angular中会出现这种情况感到困惑。
有人可以解释一下吗?或者链接解释此限制的文章?
通常javascript中的函数没有设置参数名称,所以我对为什么在Angular中会出现这种情况感到困惑。
未设置参数名称,但这不是参数的名称 - 它是现有变量的名称,由 Angular 自动生成。如果您尝试将其更改为其他内容,则它不起作用,因为您不再指向该现有对象。 它与这样的事情没有什么不同:
const $event = {/* insert object details here */}
displayCounter(count)
显然,您无法这样做,因为您尚未定义count
变量。唯一的区别是 Angular 会自动为您创建$event
变量。
至于为什么它必须是那个确切的词,它没有特殊的JavaScript含义或任何东西,它只是开发Angular的人选择用来识别他们自动生成的事件对象。
为了进一步阅读,这个问题提供了有关$event
对象以及如何在 Angular 中传递事件参数的更多详细信息。