Angular / Angular Components and Templates

Communicating Between Components

Angular applications often involve multiple components that need to communicate with each other. In this tutorial, we will learn how to pass data between components using 'Input' …

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Covers building and designing Angular components and templates.

1. Introduction

In this tutorial, we aim to understand how to pass data between components in Angular applications using 'Input' and 'Output'. Angular components interact with each other and exchange data in various ways, but for our focus, we will look at the @Input() and @Output() decorators.

You will learn:
- How to pass data from a parent component to a child component using '@Input'
- How to emit data from a child component to a parent component using '@Output' and EventEmitters.

Prerequisites: Basic understanding of Angular and TypeScript.

2. Step-by-Step Guide

Angular provides two decorators Input and Output to let parent and child components communicate.

  • Parent to Child communication - The @Input decorator in Angular allows a child component to expose a property that can be bound and passed a value by the parent component.

  • Child to Parent communication - The @Output decorator allows a child component to emit custom events back to the parent component. We also use an instance of EventEmitter to emit these custom events.

3. Code Examples

Example 1: Using @Input

Parent Component (app.component.ts)

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

@Component({
  selector: 'my-app',
  template: `
    <child-component [childMessage]="parentMessage"></child-component>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  parentMessage = "message from parent"
}

In the parent component, we bind the 'childMessage' property in the child component to the 'parentMessage' property in the parent component.

Child Component (child.component.ts)

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

@Component({
  selector: 'child-component',
  template: `
    {{childMessage}}
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  @Input() childMessage: string;
}

In the child component, we declare a property 'childMessage' with the '@Input()' decorator which will receive the value from the parent component. The child component template will display this message.

Example 2: Using @Output and EventEmitter

Child Component (child.component.ts)

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

@Component({
  selector: 'child-component',
  template: `
    <button (click)="sendMessage()">Send Message</button>
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  message = "Hola Parent!";

  @Output() messageEvent = new EventEmitter<string>();

  sendMessage() {
    this.messageEvent.emit(this.message)
  }
}

In the child component, we declare a new event 'messageEvent' with the '@Output()' decorator and emit the message when 'sendMessage()' method is called.

Parent Component (app.component.ts)

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

@Component({
  selector: 'my-app',
  template: `
    <child-component (messageEvent)="receiveMessage($event)"></child-component>
    <p>{{message}}</p>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  message:string;

  receiveMessage($event) {
    this.message = $event
  }
}

In the parent component, we listen to the 'messageEvent' from the child component and call the 'receiveMessage()' method when the event is emitted.

4. Summary

In this tutorial, we have learned how to use '@Input' and '@Output' decorators in Angular for parent to child and child to parent communication respectively. We have also learned how to use 'EventEmitter' to emit custom events.

For further learning, you can explore other ways of component interaction like using services or leveraging route parameters.

5. Practice Exercises

  1. Exercise: Create a parent component that passes a 'title' to the child component using '@Input'. The child component should display this title.

  2. Exercise: Create a child component with a button. When the button is clicked, it should emit an event with a message 'Button clicked!' to the parent component.

  3. Exercise: Combine the two exercises above. The parent component should pass a 'title' to the child component. The child component should display this title and also have a button. When the button is clicked, it should emit an event with a message back to the parent component.

Practice is key to mastering Angular. Keep exploring and building. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Backlink Checker

Analyze and validate backlinks.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help