What is the effect of adding '$' dollar sign infront of event in Angular?
onModelUpdated($event: any) {
console.log($event);
}
vs
onModelUpdated(event: any) {
console.log(event);
}
Santiago Trujillo
$
prefix in variable names has no any kind of an effect. A $
dollar sign in JavaScript (and TypeScript by extension) is a valid identifier to use as part of a variable name, it carries no syntactical meaning. It can be used in the beginning, middle or end of a variable/function name.
Specifically when it comes to $event
and its use in Angular, it is more of a convention carried over from the days of AngularJS. In AngularJS, internal variables exposed by the framework were prefixed with a $
.
That is why sometimes you see event
and other times $event
.
There was a proposal to get rid of it, but nothing happened.
So it is more of a question of style and conventions, and it is up to the personal/project preferences to come up with a convention about whether to use $event
or event
.
Using $event
as an argument when invoking the event handler (while binding events on templates) allows you to fetch the event data. It's like some kind of reserve word in Angular. If you use the event (without $
) you'll get an error.
If your handler needs this data, that's the way to get access.
Just to be crystal clear, $event
is the name of the event argument as defined in the Angular framework.
Parent directives listen for the event by binding to this property and accessing the data through the
$event
object.
The dollar sign is part of the name, hence it has to be reported as such. Once more, it is not a convention that you might follow or not, it is a name already given by the internal framework to an object and you have to call it by its name, in order to access it.
Notice that you have to use $event
in the html template, while in your class you can redefine the argument of the function as you wish.
Example from Angular docs: the event payload is necessarily written as $event
in the html template src/app/item-output/item-output.component.html
<app-item-output (newItemEvent)="addItem($event)"></app-item-output>
but then you're free to call the argument in your class (e.g src/app/app.component.ts
here) as most appropriate (in this example newItem: string
)
addItem(newItem: string) {
this.items.push(newItem);
}