Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • Making the component a template variable by giving it a name #comp, I got an empty object
  • Using the this keyword, this in this context is the parent component, generating the smaller components via ngFor
  • Sending $event as a parameter and finding the component through the path, I don't want the html element, I want the entire component and access to it's public Variables and Methods

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.

like image 850
Cedric Moore Avatar asked Sep 18 '25 12:09

Cedric Moore


2 Answers

Maybe try:

<ng-container *ngFor="let page of pages">
    <app-my-component #component (click)="pageClicked(component)"
    </app-my-component>
</ng-container>
like image 182
JackySky Avatar answered Sep 21 '25 02:09

JackySky


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

like image 26
Eliseo Avatar answered Sep 21 '25 02:09

Eliseo