Angular 2 @ViewChild devuelve undefined — ¿cómo acceder correctamente al componente hijo?
¡Hola a todos! Soy nuevo en Angular (2+) y TypeScript, y me encontré con un problema que me tiene perplejo. Intento acceder al componente hijo a través del decorador @ViewChild, pero siempre devuelve undefined.
Aquí está mi código. Tengo un componente padre `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');
}
}
}
```
Y el componente hijo `ChildComponent`:
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `
child works!
` }) export class ChildComponent { doSomething() { console.log('Haciendo algo en el componente hijo'); } } ```