Component communication patterns

As the implementation stands now, we have:

  • A basic WorkoutAudioComponent implementation
  • Augmented WorkoutRunnerComponent by exposing workout life cycle events

These two components just need to talk to each other now.

If the parent needs to communicate with its children, it can do this by:

  • Property binding: The parent component can set up a property binding on the child component to push data to the child component. For example, this property binding can stop the audio player when the workout is paused:
        <workout-audio [stopped]="workoutPaused"></workout-audio>

Property binding, in this case, works fine. When the workout is paused, the audio is stopped too. But not all scenarios can be handled using property bindings. Playing the next exercise audio or halfway audio requires a bit more control.

  • Calling functions on child components: The parent component can also call functions on the child component if it can get hold of the child component. We have already seen how to achieve this using the @ViewChild and @ViewChildren decorators in the WorkoutAudioComponent implementation. This approach and its shortcomings have also been discussed briefly in the Integrating WorkoutAudioComponent section.

There is one more not-so-good option. Instead of the parent referencing the child component, the child references the parent component. This allows the child component to call the parent component's public functions or subscribe to parent component events.

We are going to try this approach and then scrap the implementation for a better one! A lot of learning can be derived from the not-so-optimal solution we plan to implement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset