Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular pass parameter to parent component via @Output()

I have two components, let's call them contianer and itemList. The itemList has clickable items, and I need to pass click events (including the index of the clicked item) to the container.

itemList.ts:

...
@Output()
itemClicked = new EventEmitter<number>();

@Output()
somethingElse = new EventEmitter<void>();

...
this.itemClicked.emit(index);
...
this.somethingElse.emit();
...

container.html:

...
<itemList (itemClicked)="itemClicked($index)"
          (somethingElse)="somethingElse()" ... >
  ...
</itemList>
...

container.ts:

...
itemClicked(observer: Observer<number>): void {
  // where do I get the index from ?
  console.debug('itemClicked( #' + index + ')');
}

somethingElse(observer: Observer<void>): void {
  console.debug('somethingElse()');
}
...

The question is in container.ts: where do I get the index from ?

The events from somethingElse are successfully passed to the container, so this can't be totally wrong. And in fact, this is the pattern I'm trying to build the itemClicked upon. But I could not change the signature of itemClicked(...) to a correct and working version.

like image 398
Markus N. Avatar asked Oct 20 '25 22:10

Markus N.


1 Answers

I believe your issue is in the container template where you're trying to pick up $index which doesn't exist. You should use $event.

...
<itemList (itemClicked)="itemClicked($event)"
      (somethingElse)="somethingElse()" ... >
  ...
</itemList>

...

That should allow you to access the value you emit from itemClicked. Then in your container component you can access the index in it's itemClicked function:

...
itemClicked(index: number): void {
  // the index will appear here
  console.debug('itemClicked( #' + index + ')');
}

somethingElse(): void {
  // You didn't pass any argument here
  console.debug('somethingElse()');
}
...

Note that the argument is the index itself and not an observable.

Hope that helps. Good luck.

like image 135
mikias Avatar answered Oct 22 '25 11:10

mikias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!