0
0
AngularConceptBeginner · 3 min read

What is Input Decorator in Angular: Simple Explanation and Example

In Angular, the @Input decorator marks a property in a child component to receive data from its parent component. It allows components to communicate by passing values down the component tree.
⚙️

How It Works

The @Input decorator in Angular acts like a mailbox where a child component can receive messages (data) from its parent component. Imagine a parent component as a sender and the child component as a receiver. The parent sends data by setting a property on the child, and the child uses @Input to declare that it expects to receive that data.

This mechanism helps keep components separate and reusable. The child component does not need to know where the data comes from; it just declares it needs some input. The Angular framework takes care of passing the data from parent to child automatically.

💻

Example

This example shows a parent component passing a message string to a child component using @Input.

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

@Component({
  selector: 'app-child',
  template: `<p>Message from parent: {{ message }}</p>`
})
export class ChildComponent {
  @Input() message: string = '';
}

@Component({
  selector: 'app-parent',
  template: `<app-child [message]="parentMessage"></app-child>`
})
export class ParentComponent {
  parentMessage = 'Hello from Parent!';
}
Output
Message from parent: Hello from Parent!
🎯

When to Use

Use @Input when you want to send data from a parent component to a child component. This is common in Angular apps where components are nested, and the child needs to display or use information from the parent.

For example, you might use @Input to pass user details, settings, or any dynamic data that changes based on user interaction or app state. It helps keep your components modular and easy to manage.

Key Points

  • @Input marks a property to receive data from a parent.
  • It enables one-way data flow from parent to child.
  • Helps keep components reusable and independent.
  • Works with property binding syntax [propertyName] in templates.

Key Takeaways

The @Input decorator allows child components to receive data from their parent components.
It enables clear and simple communication between components in Angular.
Use @Input to pass dynamic data down the component tree.
It supports one-way data binding from parent to child.
Declaring @Input properties keeps components modular and reusable.