Skip to main content

Decorators

Table of Contents

What is a Decorator?

Decorator - function that wraps your code, easy to read and maintain

In essence, these decorators bridge the gap between parent and child components in Angular, allowing them to exchange data and react to each other's state changes.

The @Input() and @Output() decorators in Angular are used for data flow communication between components, specifically between parent and child components in a hierarchical component structure.

Here's a detailed explanation of each:

@Output: If we have two component and both have the parent child relationship, And we want to pass the data from the child to parent then on that case we can use @Output.

  • usually used with the EventEmitter and Output modules

@Input: use in the class of the child component

  • If we have two component and both have the parent child relationship, And we want to pass the data from parent to child on that case we can use @Input.

Table of Contents ⬆️

@Input() decorator:

  • Used in child components to receive data from parent components.
  • Marks a property in the child component as an input property.
  • Allows one-way data binding from parent to child.
  • The parent component can bind its data to the child component's input property using property binding syntax ([propertyName]).
  • Any changes to the parent's data will be reflected in the child component.

@Output() decorator:

  • Used in child components to emit custom events to notify parent components.
  • Marks a property in the child component as an output property.
  • Allows for two-way communication between components.
  • The child component uses an EventEmitter instance (imported from @angular/core) to emit events with data.
  • The parent component can subscribe to the child's output event using event binding syntax ((eventName)="method(\$event)").
  • When the child emits an event, the parent's subscribed method will be triggered with the emitted data.

Key points to remember:

  • @Input facilitates data flow from parent to child (one-way binding).
  • @Output enables child to notify parent and potentially send data back (two-way communication).
  • They establish a clear communication channel between components, promoting a more modular and maintainable application structure.