amit shukla

amit shukla

  • NA
  • 78
  • 66.9k

@ViewChild return undefined value.

Mar 30 2018 2:30 AM
Error : @ViewChild(CommonComponent) _comComponent:CommonComponent; viewchild is giving undefine value of _comcomponent.
 
I have a Parent component called AMLTrainingComponent and child component called CommonComponent .
 
CommonComponent has a function name setMsg. I want call child component function with in parent function but viewchild return undefine value.
 
Child Component :
  1. import { Component} from '@angular/core';  
  2. @Component({  
  3. selector:"common-app",  
  4. template:`{{errorMessage12}}`  
  5. })  
  6. export class CommonComponent {  
  7. errorMessage12: string;  
  8. setMSG(result: any)  
  9. {  
  10. this.errorMessage12 = result  
  11. }  
  12. }  
And parent component
  1. import { Component, ViewChild } from "@angular/core"  
  2. import { AMLTraingService } from '../../../bl/services/amltraining.service'  
  3. import { CommonComponent } from '../../common/common.component'  
  4. @Component({  
  5. selector: "AMLTraining-app",  
  6. providers: [AMLTraingService],  
  7. templateUrl: `/app/gecl/ComplianceSetUP/AMLTraining/AMLTraining.html`  
  8. })  
  9. export class AMLTrainingComponent {  
  10. @ViewChild(CommonComponent) _comComponent:CommonComponent; // use of child component  
  11. constructor() { }  
  12. addTopic(): void {  
  13. this._amlTrainingService.addTopic(this.amlTrainingModel).subscribe(result => {  
  14. this._comComponent.setMSG(result) // In this line this._comComponent give undefined value  
  15. });  
  16. }  
  17. }  
Parent html like below
  1. <common-app></common-app> we use common selector on parent html  
  2. <div class="page-head">  
  3. <div class="page-title">  
  4. <h1>Topic</h1>  
  5. </div>  
  6. </div>

Answers (3)