Sadra M.
Sadra M.

Reputation: 1532

When clicked on a Component, pass the Component itself as a parameter

The components are generated through an ngFor. The same click event handler is bound to all of them. I want to capture the Component on whom the user clicked inside the event handler as an argument.

Template

<div>
  <app-my-component (click)="pageClicked(<sender>)" *ngFor="let page of pages"></app-my-component>
</div>

Code Behind

pageClicked(sender: MyComponent): void {
  // sender would be the COMPONENT who called this function.
}

What I have already tried

Eventually after capturing the component, I'll want to set it's [selected] Input to true and clear the last selected component, which shouldn't be that hard if I can only get the component and store it in a local variable.

Upvotes: 3

Views: 4684

Answers (3)

Eliseo
Eliseo

Reputation: 57919

if you use a template reference variable you pass the whole component,

<app-my-component #component (click)="pageClicked(component)"..>

if you has an @OputPut use this when emitter, but rename the event (click), use e.g. (onClick)

//your component
@Output()onClick:EventEmitter<MyComponent>=new EventEmitter<MyComponent>()

clickButton(){
   this.onClick.emit(this)
}

see a fool stackbliz

Upvotes: 1

Sadra M.
Sadra M.

Reputation: 1532

Template Reference Variable

<div>
  <app-my-component #mycomponent (click)="pageClicked(mycomponent)" *ngFor="let page of pages"></app-my-component>
</div>
pageClicked(sender: MyComponent): void {
  // sender.selected is now available
}

unimportant

I tried this at first, but got an empty object, guess the project wasn't built yet...

I'll keep this here for later reference and for people asking the same question.

Upvotes: 0

JackySky
JackySky

Reputation: 333

Maybe try:

<ng-container *ngFor="let page of pages">
    <app-my-component #component (click)="pageClicked(component)"
    </app-my-component>
</ng-container>

Upvotes: 5

Related Questions