2

Consider this code (from here):

Parent component:

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);
    }
}

Child component:

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);
    }
}

As you can see in Parent component we use displayCounter($event) to receive data emitted from child component.

My question is why do we have to use $event keyword for this?
If I try to change displayCounter($event) to displayCounter(count) it is not going to work. I can however change the name of the method from displayCounter to say myAwesomeDisplayCounter. Usually functions in javascript do not have set parameter names, so I am confused as to why this is the case here in Angular.

Can somebody explain? Or link an article explaining this restriction?

E_net4
  • 27,810
  • 13
  • 101
  • 139
Tanuki
  • 717
  • 1
  • 9
  • 24

1 Answers1

6

Usually functions in javascript do not have set parameter names, so I am confused as to why this is the case here in Angular.

Parameter names aren't set, but this isn't the name of a parameter - it's the name of an existing variable, one that's automatically generated by Angular. If you try to change it to something different, it doesn't work because you aren't pointing at that existing object any more. It's no different from something like this:

const $event = {/* insert object details here */}
displayCounter(count)

Obviously you can't do that because you haven't defined a count variable. The only difference is that Angular is automatically creating the $event variable for you.

As for why it has to be that exact word, there's no special JavaScript meaning to it or anything, it's just what the people who developed Angular chose to use to identify their automatically-generated event objects.

For further reading, this question has some more details on the $event object and how event arguments are passed in Angular.

John Montgomery
  • 6,739
  • 9
  • 52
  • 68