Angular 2 @ViewChild 返回 undefined — 如何正确访问子组件?
大家好!我是 Angular (2+) 和 TypeScript 的新手,遇到了一个让我困惑的问题。我尝试通过 @ViewChild 装饰器访问子组件,但它总是返回 undefined。
这是我的代码。有一个父组件 `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');
}
}
}
```
以及子组件 `ChildComponent`:
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `
子组件
` }) export class ChildComponent { doSomething() { console.log('子组件方法被调用'); } } ```