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.

2
  • 1
    Possible duplicate of 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. Commented Mar 24, 2017 at 3:18
  • In particular, look at this answer in the duplicate target. Commented Mar 24, 2017 at 3:22

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Worked like a charm!
Perfect answer. So nothing against you, @DRiFTy, but isn't it sad that we have regressed to a level of dom manipulation abstraction far below that offered by jQuery.
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');
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.