HELPME
HELPME

Reputation: 754

How to make parent component listen for both child component changes?

I have a structure like this:

<parent-component>
   <child-component [input]="name"> </child-component>
   <child-component [input]="name> </child-component>
</parent-component>

To listen to the child component I'm using @ViewChild. The problem is that it only listens for the first child.

I made a stackblitz to reproduce the situation:

StackBlitz

There you can see that only the first "newName" is displayed to the console and not both of them. Could someone tell me what I'm doing wrong?

Upvotes: 0

Views: 1547

Answers (4)

Christoph
Christoph

Reputation: 302

I can't comment yet, but agree with Will Taylor. Please have a look here for a two-way binding example with your example. There is no need for a dependency to ChildComponent.

Upvotes: 1

Will Taylor
Will Taylor

Reputation: 1759

Really, for the situation show in your StackBlitz you should just emit an event in the child component, using an @Output and then handle that event in the parent component.

Using this method creates looser coupling between your components than ViewChild/ViewChildren, as the latter introduces the need for the parent to know more about the implementation of the child.

If you have a situation that requires the parent component to call a method on the child component, then using @ViewChildren is the correct solution, as outlined by Yash Rami's answer.

Upvotes: 0

Yash Rami
Yash Rami

Reputation: 2327

Instead of @ViewChild you can use @ViewChildren so you will get both the component data here i attach the log of the myFormValues here is the @ViewChildren doc link here you can see the console log of the object

Upvotes: 3

St&#246;ger
St&#246;ger

Reputation: 155

To listen for both, you can use two ViewChilds. Assign References to them in the .html file and specify which listener listens on which.

In your app.component.html it should be something like:

And then you can set up the listeners in your app.component.ts like so:

  @ViewChild('viewChild1') myFormValues;
  @ViewChild('viewChild2') anotherFormValues;
  informationInParentChild1;
  informationInParentChild2;

   constructor(private cdRef: ChangeDetectorRef) {}

  ngAfterViewInit() {
    this.informationInParentChild1 = this.myFormValues.myForm;
    this.informationInParentChild2 = this.anotherFormValues.myForm;
    this.cdRef.detectChanges();
  }

  submitForm() {
    console.log(this.informationInParentChild1.value);
    console.log(this.informationInParentChild2.value);
  }

I modified your stackblitz example, its working there.

Regards.

Upvotes: 1

Related Questions