Search code examples
angularangular-event-emitter

Angular 9 - Event Emitter does not emit


I am trying to pass data from a form-component to modal-component using Event Emitter. Below is how how I have configured it -

Form.ts

@Output() userEmail = new EventEmitter;

submit(order): void {
this.userEmail.emit(order.value.email);
console.log('1', order.value.email);
this.orderForm.postOrderForm(order.value);
this.openOrderFormModal();
}

Form-modal.html

<div id="order-form-modal">
    <h3>{{ 'order.form.notify.heading.1' | translate }} </h3>
    <p> {{ 'order.form.notify.msg.1' | translate }}</p>
    <p> {{ 'order.form.notify.msg.2' | translate }}</p>
    <p (userEmail)="setEmail($event)">{{email}}</p>
    <button (click)="closeOrderFormModal()" class="btn btn-outline-primary">Close</button>
</div>

Form Modal.ts

email;
setEmail(userEmail:string) {
this.email=userEmail
console.log(userEmail)
}

Below is the output I get:

enter image description here My Form Module is As follows - Form (Folder) Form.html Form.ts Form-Modal (Folder) Form-Modal.html Form-Modal.ts Please assist. If you need more info, please let me know.

Thank you! Aditya Prakash


Solution

  • You are using it wrong -

    <p (userEmail)="setEmail($event)">{{email}}</p>
    

    You cannot use a custom EventEmitter created on a component as a directive on an HTML element.

    The usage is, consider parent and child component -

    @Component({
      selector: 'app-child',
      template: ` ... some template .....   `
    })
    class ChildComponent {
    
      @Output() userEmail = new EventEmitter();         <-------------- Also, EventEmitter is a class. You need to create an instance of it
    
      submit(order): void {
          this.userEmail.emit(order.value.email);
       }
    }
    

    You can listen in parent component to the userEmail event as -

    @Component({
      selector: 'app-parent',
      template: ` <app-child (userEmail)="emailChanged($event)"></app-child>  `
    })
    class ParentComponent {
      emailChanged(userEmail:string) {
        console.log(userEmail)
      }
    }