0

Consider the following snippet of Parent's template:

<div *ngFor= "let event of events" >
     <event-thumbnail [theEvent] = 'event'></event-thumbnail>                    
</div>

Also event-thumbnail component definition is:

export class EventThumbnailComponent{
  intoroduceYourself(){
      console.log('I am X');
  }
}

In Parent component class, I want to iterate over all generated event-thumbnail elements, access the component beneath each, and call introduceYourself function on single one of them.

Josiah Keller
  • 3,635
  • 3
  • 23
  • 35
Hans
  • 2,674
  • 4
  • 25
  • 48
  • 1
    Possible duplicate of [Child listens for parent event in Angular 2](http://stackoverflow.com/questions/37677122/child-listens-for-parent-event-in-angular-2)? i.e. allow your `EventThumbnailComponent` to listen to the parents event, that way you don't have to iterate the dom elements manually. – Zze Mar 24 '17 at 03:18
  • In particular, look at [this answer](http://stackoverflow.com/a/40143881/6680611) in the duplicate target. – cartant Mar 24 '17 at 03:22

2 Answers2

3

You want to use the @ViewChildren() decorator to get a list of all instances of a specific component type within the view:

class ParentComponent implements AfterViewInit {
    @ViewChildren(EventThumbnailComponent)
    eventThumbnails: QueryList<EventThumbnailComponent>;

    ngAfterViewInit(): void {
        // Loop over your components and call the method on each one
        this.eventThumbnails.forEach(component => component.introduceYourself());

        // You can also subscribe to changes...
        this.eventThumbnails.changes.subscribe(r => {             
            // Do something when the QueryList changes
        });
    }
}

The eventThumbnails property will be updated whenever an instance of this component is added to or removed from the view. Notice the eventThumbnails is not set until ngAfterViewInit.

See the docs here for more information: https://angular.io/docs/ts/latest/api/core/index/ViewChildren-decorator.html

DRiFTy
  • 11,269
  • 11
  • 61
  • 77
0

Your child component should have @Input() theEvent to get access to the event you are passing. Then you can use the following lifecycle hook:

ngOnInit(){
   introduceYourself(){
      console.log('I am X');
   }
}
Tyler Kirby
  • 253
  • 1
  • 10