-1

我尝试使用以下子组件类

@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 中初始化组件变量是否为时已晚?

4

1 回答 1

1

我相信您正在订阅父组件中收到的事件。当您(send)="handleSend($event)"在模板中使用事件绑定签名 ( ) 时,您不必显式订阅事件。

尝试以下

父组件.html

<child (send)="handleSend($event)"></child>

父组件.ts

handleSend(event: any) {
  console.log(event);
  // no subscription is needed here
}

至于EventEmitter初始化,您可以在定义行中进行。它不影响代码。

child.component.ts

export class Child implements OnInit {
  @Output() send: EventEmitter<string> = new EventEmitter<string>();
  public constructor(){}
}
于 2020-07-15T15:01:05.617 回答