Search code examples
angularangular-componentsviewchild

Multiple template references not working using @ ViewChild in Angular 8


In my parent component I have multiple child components. Now I want to access one common function from all the child components. I am doing this by using ViewChild decorator. However I am getting the return value from 1st child component in ViewAfterInit(). But when I am trying to access the second child component, I am getting undefined.

My Parent component .ts file's code

import { Component, OnInit, Input, ViewEncapsulation, ViewChild, AfterViewInit} from '@angular/core';
import { NagivationComponent } from '../nagivation/nagivation.component';
import { CensusComponent } from '../your-data/census/census.component';
import { ApplicationComponent } from '../your-data/application/application.component';
import { ExistingPendingCoverageComponent } from '../your-data/existing-pending-coverage/existing-pending-coverage.component';

@Component({
  selector: 'app-your-data',
  templateUrl: './your-data.component.html',
  styleUrls: ['./your-data.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class YourDataComponent implements AfterViewInit{
  @Input() step;

  count:string = 'count1';
  constructor() {

  }
  @ViewChild(CensusComponent, {static: false}) census: CensusComponent;
  @ViewChild(ApplicationComponent, {static: false}) application: ApplicationComponent;
  ngAfterViewInit() {
  console.log('ApplicationComponent:'+ this.application)
    if(this.count === 'count1'){
       this.count = this.census.getSection(); 
    }
    if(this.count === 'count2'){
       this.count = this.application.getSection(); 
    }
  }

}

Parent component template file's code

<div class='container'>
  <div class='row'>
    <div class='setup-content'>
      <h1>Confirm Data/Answer Questions</h1>
      <p>Please answer all questions below. If you have questions about the data provided on this screen, please contact << Broker >> at << Phone >> or << Email >>.</p>
      <div [ngSwitch]=count>
        <app-census *ngSwitchCase="'count1'"></app-census>
        <app-application *ngSwitchCase="'count2'"></app-application>
        <app-existing-pending-coverage *ngSwitchCase="'count3'"></app-existing-pending-coverage>
      </div>
    </div>
  </div>
</div>

enter image description here

Here is the stackblitz DEMO link https://stackblitz.com/edit/new-project-zag9um?embed=1&file=app/app.component.html My question here is why I am getting 'undefined'


Solution

  • For showing the next component after clicking on the button. You need to use an EventEmitter.

    EventEmitter is the way to a child component that can communicate to its parent component.

    Angular Event Emitter Docs

    I explain below how to use EventEmitter in this case.

    My solution is available here: Solution on Stackblitz

    census.component.ts

    import { Component, EventEmitter, Output } from '@angular/core';
    
    @Component({
      selector: 'app-census',
      templateUrl: './census.component.html',
    
    })
    export class CensusComponent  {
      @Output() next: EventEmitter<string> = new EventEmitter();
    
      getSection(){
        // after clicking on getSection we need to emit the value
        // that the parent componente will receive
        this.next.emit('count2'); // <- emit count2
      }
    
    }
    
    

    your-data.component.html

    <div class='container'>
      <div class='row'>
        <div class='setup-content'>
          <h1>Confirm Data/Answer Questions</h1>
          <p>Please answer all questions below. If you have questions about the data provided on this screen, please contact << Broker >> at << Phone >> or << Email >>.</p>
          <div [ngSwitch]=count>
            <!-- here app-census pass the value to the parent component
              through onNext method ($event is the string value emitted 
              before)
            -->
            <app-census
              (next)="onNext($event)" *ngSwitchCase="'count1'"></app-census>
            <app-application *ngSwitchCase="'count2'"></app-application>        
          </div>
        </div>
      </div>
    </div>
    
    

    your-data.component.ts

    import { Component, ViewEncapsulation} from '@angular/core';
    
    @Component({
      selector: 'app-your-data',
      templateUrl: './your-data.component.html'
    
    })
    export class YourDataComponent {
    
    
      count: string = 'count1';
    
      onNext(count: string) {
        // parent component receives the value emitted by
        // census component and it stores the value in
        // this.count
        this.count = count;
        // now this.count is count2 and application component will be shown
      }
    
    }