Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create child components with NgFor then call a method of whichever emits an event

Tags:

angular

ngfor

I can think of a few ways that I might hack this but I'd like some advice on the most 'Angular' way of doing it.

I've put together an example of what I'm doing.

The main component uses NgFor to iterate over a list and create a bunch of child components.
Each child emits an event when clicked which is picked up by the parent. Each child also has a method update().

What I want is the correct way for my main component to get a reference to to whichever child emits an event and call its update() method.

Seems pretty simple (probably is pretty simple) but it is quite a central feature of the app I'm building so I want to do it as nice and clean as possible.

Cheers for you help

like image 674
popClingwrap Avatar asked Dec 03 '16 16:12

popClingwrap


1 Answers

The simplest way is to use a template variable to reference the child component:

<my-child #child *ngFor="let row of rowList;" [id]="row.name"
          (onMD)="processClick($event); child.update()"></my-child>

Updated demo: http://plnkr.co/edit/zA80iNsLHHULGx9Rbffw?p=preview

like image 57
JB Nizet Avatar answered Sep 21 '22 03:09

JB Nizet