Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Parameter $event implicitly has 'any' type

My main concern is that $event shows error in this line:

starClick($event) {

Parameter $event implicitly has 'any' type

I also wonder - according to Angular2 docs, what $event does is captures the event object, so let me ask stupid question - why we don't call it $object? Because it made me confuse quite a bit until I finally realised whats happening here..

import { Component } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'stars',
  template: `
      <span class="glyphicon glyphicon-star-empty" (click)= "starClick($event)"></span>
  `
})

export class StarsComponent {
  starClick($event) {
    if($event.target.className == "glyphicon glyphicon-star-empty") {
      $event.target.className = "glyphicon glyphicon-star";
    }
    else{
      $event.target.className = "glyphicon glyphicon-star-empty";
    }
  }
} 
like image 929
Julius Dzidzevičius Avatar asked Jun 03 '26 11:06

Julius Dzidzevičius


2 Answers

You are getting this error because of the below flag in tsconfig.json

"noImplicitAny": true

You have 2 ways to fix this.

1. "noImplicitAny": false //Make this false

2. Mention the event type in component code, for eg.

For (click)="onClick($event)" should be captured in your component as

onClick(event: KeyboardEvent)

and

(mouseover)='onMouseOver($event)' should be captured as

onMouseOver(event: MouseEvent)

like image 114
Gaurav Joshi Avatar answered Jun 06 '26 05:06

Gaurav Joshi


I think that this is a warning and not an error, that you probably see in your code editor. You can avoid this simply by putting any as type of your parameter like:

starClick($event:any) { ...

$event is a convention of Angular and you should only use it in the HTML like:

<input type="text" (yourCustomEvent)="onYourCustomEventHandle($event)">

And you can name it as you wish in the typescript code like this:

onYourCustomEventHandle(apples){ ... }

onYourCustomEventHandle(oranges){ ... }

just name it as it makes more sense to you. When using custom events you use $event to pass data to your handler.

When using it with the regular events like:

<button (click)="onClick($event)" (mouseover)='onMouseOver($event)'>

you simply get the event object as parameter in your code, but again you can name it as you wish in the code:

onClick(myClickEvent){ ... }
onClick(e){ ... }
onMouseOver(event){ ... }
onMouseOver(johnny){ ... }

But don't forget to name it always $event inside the HTML

like image 29
codtex Avatar answered Jun 06 '26 06:06

codtex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!