Explain @Input and @Output decorators.
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 ([]).
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 = '';
}
<!-- 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 (()).
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!');
}
}
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:
@Inputrepresents data flowing *down* the component tree, while@Outputrepresents events flowing *up* the component tree. - Mechanism:
@Inputuses property binding to pass values.@Outputuses event binding andEventEmitterto emit custom events.