Component Communication in Angular with @Input and @Output
2 min read

Parent component

To be able to pass data via the parent, we use two different types of data binding.

  • inputData - data that we give to the component, specified in the parent component.
  • outputData - data we get from the child.
<app-child [inputData]="person" (outputData)="getStory($event)"></app-child>

The parent component probably looks something like this.

export class ParentComponent {
	person: Person;
	story: string = "";

	getStory(story) {
		this.story = story;
	}

	// ...
}

In this case, we pass person to the child component, and receive a story from the child, and thus add it to the story property.

Child component

The child component might look something like this.

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector:  'app-child',
  template: ''
})
export class AppChild implements OnInit {
  @Input() inputData: Person;
  @Output() outputData  = new EventEmitter<string>()

  constructor() {}

  onSubmit(story: string) {
      this.outputData.emit(story);
  }
}

We receive the inputData, which in this case is a Person type. We also emit the outputData using the onSubmit method, which most likely, in this case, is a button.

We can also choose to rename the inputData if we want it to have another name in the child component.

@input("inputData") person: string;

In this case, the inputData property is aliased to person.