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

6.3k views Asked by At

I want to know briefly about event binding.

  • How can I pass an event object from template to angular component not only as a method like
    <button (click)="onClick($event)">click me</button>

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

  • I wanna know if it is possible to access DOM objects inside component like javascript like document.get.elementById('anyId') after the button was clicked and manipulate them
  • I wanna know how to pass the event object to the service class
  • Finally how to solve these bug on my code of courses.component.ts


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){*

1

There are 1 answers

0
Chetan Kotwal On

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.