【问题标题】:Unable to catch event emitted from child component in Angular 4无法捕获Angular 4中子组件发出的事件
【发布时间】:2017-08-08 13:03:01
【问题描述】:

对于我的新手问题,我很抱歉,我正在尝试使用 @Output EventEmitter 将事件从子组件发送到父组件。我无法在我的父组件中捕获该事件。

子组件

@Component({
  selector: 'app-new-attachment',
  templateUrl: './new-attachment.component.html',
  styleUrls: ['./new-attachment.component.css']
})
class NewAttachmentComponent {
  @Input('attachment') attachment: any;
  @Output() doneEditingAttachment:EventEmitter<boolean> = new EventEmitter<boolean>();

  submit() {
    console.log('done editing child');
    this.doneEditingAttachment.emit(true);
  }
}

父组件

@Component({
  selector: 'app-new-article',
  templateUrl: './new-article.component.html',
  styleUrls: ['./new-article.component.css']
})
class NewArticleComponent {
   newAttachment: any = {};
   doneEditingAttachment($event) {
     console.log('done editing parent ', $event);
   }
}

我希望有

完成编辑子

还有一个

完成编辑父项

但我只完成了对孩子的编辑

【问题讨论】:

  • html 长什么样子?
  • @Sajeetharan 我已经想通了:我忘了添加子html中的事件

标签: javascript angular typescript angular2-components


【解决方案1】:

您实际上需要使用(eventName) 表示法绑定到孩子的事件:

<app-new-attachment [attachment]="newAttachment" (doneEditingAttachment)="doneEditingAttachment($event)"></app-new-attachment>

【讨论】:

  • (doneEditingAttachment)="doneEditingAttachment($event)"
  • 我不知道为什么答案被标记为正确,但方法中必须存在“$event”参数,即
  • 如果没有给出'$event'参数,它会给出一个错误为'undefined'。编辑了主要答案。
  • @neekheel 这取决于您是否要实际使用来自$event 的值。所以根据你调用的函数,你是否添加$event
  • 是的,特别是在这种情况下,应该有 '$event' 参数,但是如果数据没有被使用,那么你是正确的,我们可以跳过 '$event' 参数
【解决方案2】:

根据您需要的commnet,

<app-new-attachment [attachment]="newAttachment" (doneEditingAttachment)="submit()"></app-new-attachment>

【讨论】:

  • (doneEditingAttachment)="doneEditingAttachment($event)"
  • 很酷,你可以在上面标记或我的,而不是发布新的答案
猜你喜欢
  • 2019-05-22
  • 2021-07-18
  • 2018-05-11
  • 2017-12-23
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
  • 2020-05-02
  • 2018-09-30
相关资源
最近更新 更多