user16579510
user16579510

Reputation:

How to pass $event object from my template to my component on Angular?

I want to know briefly about event binding.

    <button (click)="onClick($event)">click me</button>

but also as object like <button (click)="onClickObject">click me</button>



import { Component, OnInit } from '@angular/core';
import { CoursesService } from '../courses.service';

@Component({
  selector: 'app-courses',
  template:`
  <h1 id="h1id">{{ greeting }}</h1>
  <button (click)="onClick($event)">click me</button>
  `,
  styleUrls: ['./courses.component.css']
})
export class CoursesComponent implements OnInit {

greeting ="";

onClick(event){
this.greeting = "hi my name is ..."
console.log(event)
}
constructor(){
  }
  ngOnInit(): void {
  }
  }

I get an error of *Compiled with problems:X

ERROR

src/app/courses/courses.component.ts:18:9 - error TS7006: Parameter 'event' implicitly has an 'any' type.

18 onClick(event){*

Upvotes: 0

Views: 8436

Answers (1)

Chetan Kotwal
Chetan Kotwal

Reputation: 49

In the new version of Angular, we need to pass the argument type of any in-class component where we declare a function.

<button (click)="onClick($event)">Greet for Employee</button>

This one is code for the template.

onClick(event: any){ console.log(event); this.greeting="Welcome Chetan"; }

This is a code in-class component. Here When I declared a function onClick, I have taken the event as any type of argument. Try this one.

Upvotes: 1

Related Questions