Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: get single argument passed in EventEmitter

I have 2 components, a 'create' component and child 'form' component. I need the form component to pass the submit event along with the form data.

The real problem is when I log the received event, I get 2, instead of one event/arg. This is what it logs: Event {isTrusted: true} and then Contact {name: inputName}

How do I filter the events so I only act when I receive the Contact object?

Parent 'create' component:

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);
  }
}

Child 'form' component

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); }
}
like image 696
Mathius17 Avatar asked Feb 22 '16 16:02

Mathius17


1 Answers

For reference and to add more information note that in the question the Output name initially was submit matching the DOM submit event (OP renamed it in the question because of my lack of explaining the issue in my first comment) so the original problem is that the component was catching both events : The output defined by OP and the event from the form.

There's an issue (see #4059) tracking this behavior. This clearly should not happen.

The real solution, with all due respect to @Sasxa, is to rename the output to not match the DOM submit event until the issue referenced above is implemented.

like image 155
Eric Martinez Avatar answered Oct 08 '22 06:10

Eric Martinez