Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Yallaling Goudar

Communication Between Components Using Input and Output Properties

Yallaling Goudar

  • Jan 29, 2019
  • 7 Min read
  • 68,154 Views
  • Jan 29, 2019
  • 7 Min read
  • 68,154 Views
Web Development
Angular

Introduction

Communication between the Components in Angular will help you to pass data from child components to parent components and vice-versa.

Passing Data from Parent to Child Component with Input Binding

When we want to pass the data from the parent component to the child component, we use input binding with @Input decorations.

Let's consider an example where PersonChildComponent has two input properties with @Input decorations. As we can see in the below example, we must import Input from '@angular/core' library.

Filename: personchild.component.ts

1import { Component, Input } from '@angular/core';
2 
3import { Person } from './Person';
4 
5@Component({
6  selector: 'app-person-child',
7  template: `
8    <h3>{{person.name}} says:</h3>
9    <p>I, {{person.name}}, welcome to Pluralsight, {{masterName}}.</p>
10  `
11})
12export class PersonChildComponent {
13  @Input() person: Person;
14  @Input('master') masterName: string;
15}
typescript

We can use aliasing with @Input binding. As we see in the above example, masterName is aliased with the master.

Intercepting Input Property Changes with a Setter and ngOnChanges()

Intercepting input property helps to act upon a value from the parent.

Changes with setter:

Let's consider an example where we are setting the personname of the input property in the child PersonChildComponent that trims the whitespace from a name and replaces an empty value with default text.

The PersonParentComponent below demonstrates name variations in the personname, including a personname with all spaces.

Filename: personchild.component.ts

1import { Component, Input } from '@angular/core';
2 
3@Component({
4  selector: 'app-personname-child',
5  template: '<h3>"{{personname}}"</h3>'
6})
7export class PersonChildComponent {
8  private _personname = '';
9 
10  @Input()
11  set personname(personname: string) {
12    this._personname = (personname && personname.trim()) || '<no personname set>';
13  }
14 
15  get personname(): string { return this._personname; }
16}
typescript

File name: personparent.component.ts

1import { Component } from '@angular/core';
2 
3@Component({
4  selector: 'app-person-parent',
5  template: `
6  <h2>Master have {{personnames.length}} personnames</h2>
7  <app-person-child *ngFor="let personname of personnames" [personname]="personname"></app-person-child>
8  `
9})
10export class PersonParentComponent {
11  // Displays 'Yallaling', '<no person set>', 'Goudar'
12  personnames = ['Yallaling', '   ', '  Goudar  '];
13}
typescript

Changes with ngOnChanges():

ngOnChanges() method of the OnChanges lifecycle hook interface detects and acts upon changes to input property values. You may prefer this approach to the property setter when watching multiple, interacting input properties.

Let's consider an example where we have MinmaxChildComponent which detects changes to the minimum and maximum input properties and composes a log message reporting these changes.

Filename: minmaxchild.component.ts

1import { Component, Input, OnChanges, SimpleChange } from '@angular/core';
2
3@Component({
4  selector: 'app-minmax-child',
5  template: `
6    <h3>Min value: {{minimum}} Max value: {{maximum}}</h3>
7    <h4>Change log:</h4>
8    <ul>
9      <li *ngFor="let change of changeLog">{{change}}</li>
10    </ul>
11  `
12})
13export class MinmaxChildComponent implements OnChanges {
14  @Input() minimum: number;
15  @Input() maximum: number;
16  changeLog: string[] = [];
17
18  ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
19    let log: string[] = [];
20    for (let propName in changes) {
21      let changedProp = changes[propName];
22      let to = JSON.stringify(changedProp.currentValue);
23      if (changedProp.isFirstChange()) {
24        log.push(`Initial value of ${propName} set to ${to}`);
25      } else {
26        let from = JSON.stringify(changedProp.previousValue);
27        log.push(`${propName} changed from ${from} to ${to}`);
28      }
29    }
30    this.changeLog.push(log.join(', '));
31  }
32}
typescript

The MinmaxChildComponent supplies the minimum and maximum values and binds buttons to methods that change them.

Filename: minmaxparent.component.ts

1import { Component } from '@angular/core';
2
3@Component({
4  selector: 'app-minmax-parent',
5  template: `
6    <h2>Source code minmax</h2>
7    <button (click)="changedMin()">New minimum value</button>
8    <button (click)="changedMax()">New minmax value</button>
9    <app-minmax-child [major]="major" [minor]="minor"></app-minmax-child>
10  `
11})
12export class MinmaxParentComponent {
13  minimum = 1;
14  maximum = 23;
15
16  changedMin() {
17    this.minimum++;
18  }
19
20  changedMax() {
21    this.maximum++;
22    this.minimum = 0;
23  }
24}
typescript

When we click on the button 'New minimum value', the minimum value will get increased and when we click on the button 'New maximum value', the maximum value will get increased. And we can see the changed values getting logged in the changelog.

Passing Data from Child to Parent with Output Binding

An Output is an observable property annotated with an @Output decorator, the property always returns an Angular EventEmitter. Values flow out of the component as events bound with an event binding.

In Angular, a component can emit an event using @Output an EventEmitter. Both are parts of the @angular/core.

Let's consider an example where we are emitting the sum value from the component ExampleChildComponent.

Filename: examplechild.component.ts

1import { Component, EventEmitter, Output } from '@angular/core';
2@Component({
3    selector: 'app-example-child',
4    template: `<button class='btn btn-primary' (click)="changeValue()">Click me</button> `
5})
6export class ExampleChildComponent {
7    @Output() valueChange = new EventEmitter();
8    sum = 0;
9    changeValue() { 
10        // You can give any function name
11        this.sum = this.sum + 10;
12        this.valueChange.emit(this.sum);
13    }
14}
typescript

Let's consider an example where we are going to emit an event and pass a parameter to the event. In the below example, we are emitting a value from ExampleChildComponent to ExampleComponent. Displaying the sum value from ExampleChildComponent.

Filename: example.component.ts

1import { Component, OnInit } from '@angular/core';
2@Component({
3    selector: 'app-example',
4    template: `<app-example-child (changeValue)='displaySum($event)'></app-example-child>`
5})
6export class ExampleComponent implements OnInit {
7    ngOnInit() {
8    }
9    displaySum(sum) {
10        console.log(sum);
11    }
12}
typescript

Conclusion

In this guide, we have explored the Input and Output Property techniques in Angular. We have also seen different methods or ways through which we can pass the values from parent to child component and vice-versa.

You can learn more about Angular binding in my guide Attribute, Class, and Style Bindings in Angular.