【问题标题】:Angular2: get single argument passed in EventEmitterAngular2:获取在 EventEmitter 中传递的单个参数
【发布时间】:2023-03-03 11:09:01
【问题描述】:

我有 2 个组件,一个“创建”组件和一个子“表单”组件。我需要表单组件将提交事件与表单数据一起传递。

真正的问题是当我记录收到的事件时,我得到 2,而不是一个事件/参数。这是它记录的内容:Event {isTrusted: true},然后是 Contact {name: inputName}

如何过滤事件,以便仅在收到联系人对象时才采取行动?

父“创建”组件:

import {Component, OnInit } from 'angular2/core';
import {Contact} from './contact';
import {ContactFormComponent} from './contact-form.component';

@Component({
    selector: 'contact-create',
    template: `
      <h2>Nuevo contacto</h2>

      <div class="panel panel-default">
        <div class="panel-body">

          <contact-form [contact]="contact" (formSubmitted)="saveContact($event)"></contact-form>

        </div>
      </div>
    `,
    directives: [ContactFormComponent]
})
export class ContactCreateComponent {

  contact: Contact = new Contact('');

  constructor(
      private router: Router,
      private contactService: ContactService) { }

  saveContact(args) {
    console.log(args);
  }
}

子“表单”组件

import {Component, EventEmitter} from 'angular2/core';
import {NgForm}    from 'angular2/common';
import {Contact}   from './contact';

@Component({
  selector: 'contact-form',
  inputs: ['contact'],
  outputs: ['formSubmitted'],
  templateUrl: 'app/contacts/contact-form.component.html',
})
export class ContactFormComponent {

  contact: Contact;
  formSubmitted: EventEmitter<any> = new EventEmitter();

  onSubmit(contact) { this.formSubmitted.next(contact); }
}

【问题讨论】:

  • 如果您将输出重命名为不匹配默认的submit event ;)
  • 我不够清楚。您的问题是因为您的输出与默认提交事件匹配,这就是它触发两次的原因。通过重命名您的输出(正如您在问题中所做的那样),您应该不再有问题了。
  • 这就是实际发生的事情!谢谢@EricMartinez
  • 不客气!仅供参考,已经有一个 issue 跟踪此行为。

标签: angular eventemitter angular2-forms


【解决方案1】:

作为参考和添加更多信息,请注意问题中的输出名称最初是 submitDOM submit event 匹配(由于我没有在我的 first comment 中解释问题,所以在问题中将其重命名为 OP)所以最初的问题是组件同时捕获了两个事件:OP 定义的输出和表单中的事件。

跟踪此行为存在问题(请参阅#4059)。这显然不应该发生。

在充分尊重@Sasxa 的情况下,真正的解决方案是重命名输出,使其与 DOM 提交事件不匹配,直到实现上述问题。

【讨论】:

  • 你说得对,我专注于日志输出,甚至没有注册事件名称(;
  • 我也被这个咬了。将输出事件名称保持为“提交”会捕获两次。几乎要拉我的头发。感谢@Eri Martinez 和 Mathius 提出 SO。 +1
猜你喜欢
  • 2016-05-25
  • 1970-01-01
  • 2017-04-21
  • 2019-03-12
  • 1970-01-01
  • 2017-08-12
  • 2016-11-05
  • 1970-01-01
  • 2016-09-09
相关资源
最近更新 更多