cerealex
cerealex

Reputation: 1691

Call multiple children methods from parent component

I'm trying to call children methods from parent component with ViewChild:

...

export class Parent {
  @ViewChild(ProfileImageComponent) profileImage: ProfileImageComponent;
  ...

  updateProfile() {
    ...
    this.profileImage.updateAvatar();
  }
}

The problem is this only works for the first child component instance in the parent's view:

...
<profile-image></pofile-image> <!-- only this one gets updated -->
...
<profile-image></pofile-image>
...
<profile-image></pofile-image>
...

How can I call every profileImage children method so everything gets updated?

Upvotes: 4

Views: 4013

Answers (2)

Hasan Fathi
Hasan Fathi

Reputation: 6096

Use @ViewChildren from @angular/core to get a reference to the components.

template:

<profile-image #profile></pofile-image>
<profile-image #profile></pofile-image>
<profile-image #profile></pofile-image>

Component:

import { ViewChildren, QueryList } from '@angular/core';

@ViewChildren('profile') components:QueryList<ProfileImage>;

ngAfterViewInit(){
    // call method
   this.components.forEach(ProfileImage => {
          ProfileImage.updateAvatar();
   }); 
}

Upvotes: 15

Sano Litch
Sano Litch

Reputation: 633

You can set names to child components like:

<profile-image #child1></pofile-image> 
...
<profile-image #child2></pofile-image>
...
<profile-image #child3></pofile-image>

And declare it in parent:

@ViewChild('child1') profileImage1: ProfileImageComponent;
@ViewChild('child2') profileImage2: ProfileImageComponent;
@ViewChild('child3') profileImage3: ProfileImageComponent;

updateProfile() {
    ...
    this.profileImage1.updateAvatar();
    this.profileImage2.updateAvatar();
    this.profileImage3.updateAvatar();
  }

Upvotes: -1

Related Questions