Dmitry Samoylov
Dmitry Samoylov

Reputation: 1318

How can I handle all the clicks on the component in angular4?

I want to handle all the clicks on the component in one method. How could I do that?

I have a component that represents single table row and its template looks like

<td style="text-align: right;">{{item.id}}</td>
<td style="text-align: right;">{{item.name}}</td>
<td style="text-align: right;">{{item.amount}}</td>

I want to catch all the clicks that could occur anywhere (any td). How could I do that?

Parent template is

<table>
  <tbody>
    <ng-template ngFor let-item [ngForOf]="itemsCollection">
      <app-tr [item]="item" style="display: table-row"></app-tr>
    </ng-template>
  </tbody>
</table>

I can add (click)="someParentMethod($event)" to the parent template, but I want to handle the event by the child component.

Upvotes: 1

Views: 58

Answers (2)

Shailesh Ladumor
Shailesh Ladumor

Reputation: 7252

you also add click event of child component and send event from child to parent via EventEmiiter

for example

Child component

@Output onClick: EventEmiiter<any> = new EventEmiiter();

onclicking(){
this.onClick.emit('pass here you want');
}

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657731

Add this code to your app-tr components class

@HostListener('click', ['$event'])
myClickHandler(event) {...}

Upvotes: 1

Related Questions