Hans Hans -4 years ago 116
Javascript Question

Angular.js 2: Access component of a directive

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download