【发布时间】:2020-06-17 23:33:24
【问题描述】:
child.component.ts
currentPage = 1;
parent.component.ts
export class ParentComponent implements OnInit, AfterViewInit {
@ViewChild(ChildComponent, {static: false}) child;
ngAfterViewInit() {
console.log(this.child.currentPage); // throws error
}
parent.component.ts
<app-child></app-child>
我尝试设置超时,但也没有用。
ERROR TypeError: Cannot read property 'currentPage' of undefined
我做错了什么?
【问题讨论】:
-
添加子组件的类型:``` @ViewChild(ChildComponent, {static: false}) child: ChildComponent ``
-
这也经常发生在我身上。确保孩子不在 ngIf 内并且不在订阅后,如果它是你必须在设置后等待,否则不可用。
-
@shAkur,如果您的 ChildComponent 不在 Angular 中,因为您有一个 *ngIf="condition" -并且条件一开始是错误的,给您一个错误 - 您可以使用 if @987654325 来解决@,傻逼例子stackblitz.com/edit/…
-
父组件内部子组件的引用确实是有条件的:。我的孩子参考在 withoutResults ng 模板中:(
标签: angular components undefined lifecycle viewchild