Receiving events from parent component inside child component projected via ng-content

536 views Asked by At

Consider this simplified situation, we have:

Parent component template (selector: 'parent'):

<div class="wrapper">
  <input (blur)="onBlur()"/>
  <ng-content></ng-content>
</div>

Child component template (selector: 'child'):

<div>{{ valueEmittedFromParentInputOnBlurEvent }}</div>

Usage, somewhere on a page:

<parent>
  <child></child>
</parent>

I'd like to handle valueEmittedFromParentInputOnBlurEvent in my child component after it was emitted in onBlur() event. Please, help me if you can :)

2

There are 2 answers

1
Rikhil Arora On

You can use a service or provide an Input to your Child Component.

1
Mohammad Mehdi Mohammadi On

Follow this concept to have communication between parent and child:

  1. In your html parent component:
<child #child></child>
<input (blur)="child.onBlurEvent()"/>

you define your child component as #child to access its methods like onBlurEvent()

  1. In your ts child component
number = 0;
onBlurMethod() {
    this.number++;
}
  1. In your html child component
<h1>{{number}}</h1>

when onBlur event occurs in your parent it will call onBlurEvent method in child and the method will do whatever it must do

this was an example to help you to understand about parent and child communication, this concept will help you to solve your problem, good luck