我尝试使用以下子组件类
@Component({
selector: 'child',
templateUrl: './child.component.html'
})
export class Child implements OnInit {
@Output() send: EventEmitter<string>;
public constructor(){}
public ngOnInit() {
send = new EventEmitter<string>();
}
public onEventXYZ() {
this.send.emit('hello');
}
}
在父模板中,我将上述组件引用为
<child (send)="handleSend($event)"></child>
它导致了这个错误:Cannot read property 'subscribe' of undefined...
页面加载。当我后来根据朋友的建议,将 EventEmitter 初始化从 ngOnInit 移到构造函数时,一切正常。
那么,在 ngOnInit 中初始化组件变量是否为时已晚?