Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Click $event with Extra Parameters

Tags:

angular

Is it possible to capture the $event parameter on a click event and also pass in some extra parameter data to a component method?

Example template:

<div *ngFor="let item of data" (click)="onItemClick($event, item)">     {{ item.Name }} </div> 

Example component:

onItemClick(event, item) {     // do something } 
like image 351
jcosgrave Avatar asked Oct 09 '17 11:10

jcosgrave


People also ask

How do you pass parameters in event emitter?

For passing the parameters, we will wrap all the parameters inside the curly brackets (this will combine them as a single object) and pass it to the emit method. To receive the parameters in the parent component, we will make a similar type of object and update its value with that of the received object.

What does $event do in Angular?

The $event object often contains information the method needs, such as a user's name or an image URL. The target event determines the shape of the $event object. If the target event is a native DOM element event, then $event is a DOM event object, with properties such as target and target.

How Onclick works in Angular?

Introduction to AngularJs onclick The ng-click directive can be used with multiple HTML elements such as button, input, select, checkbox, etc. This provides the developer ability to define custom behavior whenever an element is clicked.

How does Angular handle click event?

Events are handled in Angular using the following special syntax. Bind the target event name within parentheses on the left of an equal sign, and event handler method or statement on the right. Above, (click) binds the button click event and onShow() statement calls the onShow() method of a component.


2 Answers

Yes it would work fine. But keep the order of parameters same.

<div *ngFor="let item of data" (click)="onItemClick($event, item)"> 

In this case the second element is your passed element.

onItemClick(event, item) {   console.log("Checking passed item: ",item); } 
like image 90
Ali Turab Abbasi Avatar answered Sep 19 '22 06:09

Ali Turab Abbasi


Yes It will work fine. Put console.log inside the function and check.

onItemClick(event, item) {   console.log("Event: ",event,"Item: ",item); } 
like image 41
sathish94us Avatar answered Sep 21 '22 06:09

sathish94us