7. Listen to child component events

In this section we will listen to child component events emitted to the parent.

1. Add event emitter to component

The EventEmitter in Angular is used to emit event from child components to parent components and can pass what ever object, array primitive, null or anything you would like. Event emitters are made by using Angular's@Output decorators. We will address the other side of the equation about passing in data to the component with property binding later in the course using the opposite with @Input decorators.

  • Add event emitter to component

  • Emit add attendee event when the form is submitted by the submit method.

src/app/event/components/add-attendee/add-attendee.component.ts
import { Component, EventEmitter } from '@angular/core';
import { Output } from '@angular/core';
import { Attendee } from '../../../models';
import { FormGroup } from '@angular/forms';
import { FormControl } from '@angular/forms';
import { Validators } from '@angular/forms';

@Component({
  selector: 'app-add-attendee',
  templateUrl: './add-attendee.component.html',
  styleUrls: ['./add-attendee.component.scss']
})
export class AddAttendeeComponent {
  @Output()
  addAttendee = new EventEmitter<Attendee>();

  addAttendeeForm = new FormGroup({
    name: new FormControl('', [Validators.required])
  });

  submit() {
    const attendee = {
      name: this.addAttendeeForm.value.name,
      attending: true,
      guests: 0
    };
    this.addAttendee.emit(attendee);
  }
}

2. Add event listener to add-event-component selector

  • Add the event listener to the add-event-component selector. The $event is an angular specific variable which is a generic name for what ever you emitted from the child component.

src/app/event/containers/event/event.component.html
<app-add-attendee (addAttendee)="addAttendee($event)"></app-add-attendee>

3. Add method to call when event is emitted

Note we recreate the array every time versus using an array .push method which would mutate the array.

  • Add a addAttendee method to the component.

  • Declare a attendees property on the class and initialise it to an empty array.

/src/app/event/containers/event/event.component.ts
import { Component, OnInit } from '@angular/core';
import { Attendee } from '../../../models';

@Component({
  selector: 'app-event',
  templateUrl: './event.component.html',
  styleUrls: ['./event.component.scss']
})
export class EventComponent implements OnInit {
  attendees: Attendee[] = [];
  constructor() {}

  ngOnInit() {}

  addAttendee(attendee: Attendee) {
    this.attendees = [...this.attendees, attendee];
    console.log('TCL: EventComponent -> addAttendee -> this.attendees', this.attendees);
  }
}

Last updated