考虑这个代码(来自这里):
父组件:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
子组件:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
正如您在父组件中看到的,我们displayCounter($event)用来接收从子组件发出的数据。
我的问题是为什么我们必须为此使用$event关键字?
如果我试图改变displayCounter($event)到displayCounter(count)它是行不通的。但是,我可以将方法的名称从displayCountersay更改为myAwesomeDisplayCounter. 通常 javascript 中的函数没有设置参数名称,所以我很困惑为什么在 Angular 中会出现这种情况。
有人可以解释一下吗?或者链接一篇解释这个限制的文章?
通常 javascript 中的函数没有设置参数名称,所以我很困惑为什么在 Angular 中会出现这种情况。
参数名称未设置,但这不是参数的名称 - 它是现有变量的名称,由 Angular 自动生成。如果您尝试将其更改为不同的内容,它将不起作用,因为您不再指向该现有对象。它与这样的事情没有什么不同:
const $event = {/* insert object details here */}
displayCounter(count)
Run Code Online (Sandbox Code Playgroud)
显然你不能这样做,因为你没有定义一个count变量。唯一的区别是 Angular 会自动$event为您创建变量。
至于为什么它必须是那个确切的词,它或任何东西都没有特殊的 JavaScript 含义,这只是开发 Angular 的人选择用来识别他们自动生成的事件对象的词。
为了进一步阅读,这个问题有更多关于$event对象的细节以及如何在 Angular 中传递事件参数。
| 归档时间: |
|
| 查看次数: |
1059 次 |
| 最近记录: |