Avatar ·

Angular 2 @ViewChild returns undefined — how to properly access a child component?

Hello everyone! I'm new to Angular (2+) and TypeScript, and I've run into a problem that has me stumped. I'm trying to access a child component via the @ViewChild decorator, but it keeps returning undefined. Here is my code. I have a parent component `ParentComponent`: ```typescript import { Component, ViewChild, AfterViewInit } from '@angular/core'; import { ChildComponent } from './child.component'; @Component({ selector: 'app-parent', template: `
` }) export class ParentComponent { @ViewChild(ChildComponent) childComponent!: ChildComponent; callChildMethod() { if (this.childComponent) { this.childComponent.doSomething(); } else { console.log('childComponent is undefined'); } } } ``` And the child component `ChildComponent`: ```typescript import { Component } from '@angular/core'; @Component({ selector: 'app-child', template: `

Child component works!

` }) export class ChildComponent { doSomething() { console.log('Doing something in child'); } } ```