Why component dont display variable of another component?

I have 2 components: AppComponent and export class InnerComponent. AppComponent embed InnerComponent via @ViewChild. After that i need display to console variables value from InnerComponent. However i get error message to console because this.InnerComponent is undefined.

Please help me display a variable to console from AppComponent.


import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { InnerComponent } from './inner/inner.component';

  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
export class AppComponent implements AfterViewInit {
  @ViewChild(InnerComponent) innerComponent: InnerComponent;

  ngAfterViewInit() {
    console.log(this.innerComponent); // undefined
    console.log(this.innerComponent.a); // error


import { Component } from '@angular/core';

  selector: 'app-inner',
  templateUrl: './inner.component.html',
  styleUrls: ['./inner.component.css'],
export class InnerComponent {
  a = 200;
}`enter code here`

live demo


  • Your app.component.html template doesn't actually contain the <app-inner> component. If you haven't put it in the template, it's not a child you can select with @ViewChild

    Your template looks like this:

    <div class="app">app:</div>

    But it should look like this so the element can be selected

    <div class="app">

    Live Demo