Angular Child Parent Child Communication with @ViewChild

Overview

Although there is a way for siblings to communicate, there is also the option for a child to emit data to a parent component which can update another child component.

In this scenario you have a layout (Parent Component) with a form (Child Component) and a data table (Child Component). The form will emit data to the parent and the parent will execute a function in the child table component.

Parent Layout Component

Import the child components to the parent component .

import { Component, ViewChild, OnInit } from '@angular/core';
import { ChildTableComponent } from './../child-table/child-table.component';

Then add the @ViewChild decorators to Parent component.

@ViewChild(ChildTableComponent , {static: false}) childTopTenComp: ChildTableComponent;
fromChildFormActionChange($event): void {
    this.searchString = $event;
    this.ChildTableComponent.loadData(this.searchString, this.childColumnVal);

WARNING! If you get an initialization error for the @ViewChild element then you may need to add an exclamation mark ! after the variable name. I noticed this with Angular version 12 which was release in November 2021.

Example: childTopTenComp!

@ViewChild(ChildTableComponent, {static: false}) childTopTenComp!: ChildTableComponent;

Child Form Component

Import the following:

import { Component, Output, EventEmitter } from '@angular/core';

Also add the Output decorator under the export class section in the form child component.

@Output() actionChange = new EventEmitter();

Then add a function to emit a change to the parent component.

onSubmit(searchStr: string) {
  this.actionChange.emit(searchStr);
}

From the HTML template

<app-child-form (actionChange)='fromChildFormActionChange($event) />

Child Table Component

Under the export child component section

loadData(searchStr: string)
{
  console.log('From Search Form: ', searchStr);

WARNING!

This will not work between Feature Modules including a Shared Module . If there is a way to configure a Shared Module to be able to have a method accessed from another module please post the solution.
Thank you. If you want to see a post on Shared Modules please go here