🅰️ Angular Q42 / 125

Explain @Input and @Output decorators.

AI-Powered Answer ✓ Answered

In Angular, `@Input` and `@Output` are fundamental decorators used for communication between components. They enable hierarchical data flow, allowing components to share data and events in a clear and organized manner, facilitating reusable and maintainable component architectures.

@Input Decorator

The @Input decorator is used to pass data from a parent component to a child component. It allows a child component to receive data from its parent, making the child component reusable and configurable.

To use @Input, you decorate a property in the child component with @Input(). The parent component can then bind to this property using property binding syntax ([]).

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

@Component({
  selector: 'app-child',
  template: `
    <p>Child Component</p>
    <p>Received message: {{ message }}</p>
  `
})
export class ChildComponent {
  @Input() message: string = '';
}
html
<!-- parent.component.html -->
<app-child [message]="'Hello from Parent!'"></app-child>

@Output Decorator

The @Output decorator is used to send data or events from a child component to a parent component. It allows the child component to notify its parent about changes or actions that have occurred within itself.

To use @Output, you decorate a property in the child component with @Output(). This property must be an instance of EventEmitter. The child component uses the .emit() method of this EventEmitter to send data, and the parent component listens for these events using event binding syntax (()).

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

@Component({
  selector: 'app-child',
  template: `
    <button (click)="sendMessageToParent()">Send Message</button>
  `
})
export class ChildComponent {
  @Output() messageEvent = new EventEmitter<string>();

  sendMessageToParent() {
    this.messageEvent.emit('Hello from Child!');
  }
}
typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <app-child (messageEvent)="receiveMessageFromChild($event)"></app-child>
    <p>Received from child: {{ childMessage }}</p>
  `
})
export class ParentComponent {
  childMessage: string = '';

  receiveMessageFromChild(message: string) {
    this.childMessage = message;
  }
}

Key Differences and Use Cases

  • @Input: For parent-to-child communication. Use when the parent needs to provide data to the child.
  • @Output: For child-to-parent communication. Use when the child needs to notify the parent about an event or pass data back.
  • Data Flow: @Input represents data flowing *down* the component tree, while @Output represents events flowing *up* the component tree.
  • Mechanism: @Input uses property binding to pass values. @Output uses event binding and EventEmitter to emit custom events.