DeployU
Interviews / Frontend Engineering / What are the different ways to communicate between components in Angular?

What are the different ways to communicate between components in Angular?

conceptual Components Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are building a new feature that consists of two components: a parent component and a child component.

You need to find a way to pass data from the parent component to the child component, and you also need to find a way to notify the parent component when an event occurs in the child component.

The Challenge

Explain the different ways to communicate between components in Angular. What are the pros and cons of each approach, and which one would you choose for this use case?

Wrong Approach

A junior engineer might try to solve this problem by using a shared service. This would work, but it would be overkill for this simple use case.

Right Approach

A senior engineer would know that there are several different ways to communicate between components in Angular. They would be able to explain the pros and cons of each approach and would have a clear recommendation for which one to use in this use case.

Step 1: Understand the Key Communication Patterns

PatternDescription
@Input()To pass data from a parent component to a child component.
@Output()To emit an event from a child component to a parent component.
ViewChildTo get a reference to a child component in the parent component.
ServiceTo share data between components that are not directly related.

Step 2: Choose the Right Tool for the Job

For our use case, we should use a combination of @Input() and @Output().

  • We will use @Input() to pass data from the parent component to the child component.
  • We will use @Output() to emit an event from the child component to the parent component.

Step 3: Code Examples

Here’s how we can use @Input() and @Output() to communicate between a parent and a child component:

child.component.ts:

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

@Component({
  selector: 'my-child',
  template: `
    <p>{{ myInput }}</p>
    <button (click)="myEvent.emit('hello from child')">Click me</button>
  `
})
export class MyChildComponent {
  @Input() myInput: string;
  @Output() myEvent = new EventEmitter<string>();
}

parent.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'my-parent',
  template: `
    <my-child [myInput]="'hello from parent'" (myEvent)="onMyEvent($event)"></my-child>
  `
})
export class MyParentComponent {
  onMyEvent(message: string) {
    console.log(message);
  }
}

Practice Question

You want to share data between two components that are not directly related. Which of the following would you use?