繁体   English   中英

@Output childEvent 未初始化

[英]@Output childEvent not initialized

我对 Angular 世界还很陌生,正在研究 angular 7,我正在做一些示例,其中组件共享数据,父到子部分工作正常,但是当我尝试将任何值从子级发送到父级时,它不起作用。

它向我展示了这个错误在此处输入图片说明

应用组件.html

<div>{{show}}</div>

<app-communicating-components [Parent]="message" (childEvent)="getMessage($event)"></app-communicating-components>

app-component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'AngularLesson2';

  public message = 'Hello my child, Parents here';
  public show: string;


  getMessage($event) {
    this.show = $event;
  }
}

通信components.component.html

<p>
  {{Parent}}
</p>
<button (click)="fireEvent()">Fire from child</button>

通信components.component.ts

import { Component, OnInit, Input, Output } from '@angular/core';
import { EventEmitter } from 'events';

@Component({
  selector: 'app-communicating-components',
  templateUrl: './communicating-components.component.html',
  styleUrls: ['./communicating-components.component.css']
})
export class CommunicatingComponentsComponent implements OnInit {

  @Input() Parent;
  @Output() public childEvent = new EventEmitter();


  constructor() {
  }

  ngOnInit() {

  }

  fireEvent() {
    this.childEvent.emit('Hi, I am child');
    console.log("event fire" + this.childEvent);
  }

}

我在这里做错了什么?

我相信问题出在你的 import import { EventEmitter } from 'events'; 不是你应该在这里导入的。 尝试将导入更改为import { EventEmitter } from '@angular/core';

更新

这是一个stackblitz 示例,显示它有效

对于 Angular 的较新版本,例如 8,您必须:

  1. 如 ks 所说,正确导入发射器: import { EventEmitter } from '@angular/core'
  2. 为输出初始化发射器: @Output() emisor = new EventEmitter<type>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM