3
Answers

Pass a variable from child to parent component

Maureen Moore

Maureen Moore

4y
508
1
So I am trying to get a value from my child component to print in my parent component and I tried the following:
In my child component ts:
  1. export class ChildComponent {  
  2. message: string = 'Hello!!!';  
  3. }  
In my parent component ts:
  1. import { Component, ViewChild, AfterViewInit} from '@angular/core';  
  2. import { ChildComponent } from '../child/child.component'  
  3.   
  4. export class ShoppingCartComponent implements ControlValueAccessor, AfterViewInit {  
  5. messageFromChild : string;  
  6. @ViewChild(ChildComponent) myChild;  
  7. ngAfterViewInit() {  
  8. this.messageFromChild = this.myChild.message;  
  9. }  
  10. }  
In my parent component html:
  1. <h1> From Child - {{ messageFromChild }} </h1>  
I don't get any errors but {{ messageFromChild }} is blank.

Answers (3)