Angular:为什么在ngAfterContentInit之后该变量是未定义的?
Angular:为什么在ngAfterContentInit之后该变量是未定义的?
我正在尝试使用@ContentChild获取ng-content的内容。为了更好地理解@ContentChild,我尝试实现了一个简单的代码示例。我还进行了一些研究,例如在这里What's the difference between @ViewChild and @ContentChild?,以及其他许多页面,但我已经花了几个小时了,并且遇到了以下问题。
如果我想在控制台输出变量this.child
,那么会显示undefined
。为什么会这样,我做错了什么?我需要做什么不同的操作?
app-root:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `` }) export class AppComponent {}
app-parent:
import { AfterContentInit, Component, ContentChild} from '@angular/core'; import { ChildComponent } from './child/child.component'; @Component({ selector: 'app-parent', template: `` }) export class ParentComponent implements AfterContentInit { @ContentChild('refChild') child: any; ngAfterContentInit() { console.log('ngAfterContentInit'); console.log(this.child); } }
app-child:
import { Component} from '@angular/core'; @Component({ selector: 'app-child', template: `Child headline
Child subheadline
` }) export class ChildComponent {}
Angular中的问题:为什么ngAfterContentInit之后变量变为undefined?
问题原因:
问题出现的原因是在父组件和子组件之间的通信中出现了错误。在父组件中,我们试图通过ViewChild装饰器来引用子组件,但是在ngAfterContentInit生命周期钩子函数中,子组件的变量却变成了undefined。
解决方法:
要解决这个问题,我们需要将ViewChild装饰器放在子组件的直接上方。这样,子组件的变量就不会再变成undefined了。修改后的代码如下:
另外,如果我们想要在父组件中引用子组件,可以使用服务(Services)、事件发射器(EventEmitter)或者Host装饰器。例如,在子组件的构造函数中使用Host装饰器可以实现这个功能,代码如下:
constructor(@Host() parent: ParentComponent) { console.log("Here it is", parent) }
如果我们仍然想要从父组件到子组件的方向进行通信,可以使用事件发射器、服务或者Host装饰器。在我的更新的回答中有详细说明,可以参考。
注意:在子组件中使用ViewChild装饰器只能实现从子组件到父组件的通信,无法实现反向通信。