Skip to content
Advertisement

ViewChild is undefined in angular 13

I am trying to call view child of a child component from parent and getting undefined in the console.

see the image also see the stack blaze for the same

https://stackblitz.com/edit/angular-ivy-k4m2hp?file=src%2Fapp%2Fhello.component.ts

see the image also see the stack blaze for the same

import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { TestChildComponent } from './test-child/test-child.component';

@Component({
  selector: 'hello',
  template: `<h1>this is Hello component {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
  @Input() name: string;
@ViewChild('TestChildComponent') testChildComponent: TestChildComponent
  ngOnInit() {
    console.log('calling ngOninit in hello component');
    console.log('going to call test child instance this.TestChildComponent.ngOninit')
   console.log(this.testChildComponent);
  }
}

Please help to get the child component

this.testChildComponent

So that i can call ngOnInit of child from parent.

this.testChildComponent.ngOnInit()

Advertisement

Answer

if you set your viewChild { static: true } you will be able to access it in ngOnInit

but in your sample the issue is due totestChildComponent is a child of app.component and not hello.component

<app-test-child childname="{{ name }}" #test></app-test-child>

app.component.ts

import { Component, VERSION, ViewChild } from '@angular/core';
import { TestChildComponent } from './test-child/test-child.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'this is from app compoenent';
  @ViewChild('test', { static: true }) testChildComponent: TestChildComponent;

  ngOnInit() {
    console.log('calling ngOninit in app component');
    console.log(this.testChildComponent);
  }
}

If you want to access testChildComponent from hello.component you will have to send it the component as an input for sample

following a working sample of accessing testChildComponent

https://stackblitz.com/edit/angular-ivy-tvwukg?file=src%2Fapp%2Fapp.component.html

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement