Advance Angular Lecture 5
Advance Angular Lecture 5
17
5. Input() / Output() Decorators
INPUT DECORATOR
The @Input() decorator in Angular is used to define an input property in a component. When a
component has input properties decorated with @Input(), it can receive values from its parent component.
These input properties allow data to flow into the component from the outside. The parent component can
bind values to these input properties using property binding in the template. This enables communication
from the parent component to the child component.
OUTPUT DECORATOR
The @Output() decorator in Angular is used to define an output property in a component. When a
component has output properties decorated with @Output(), it can emit events to its parent component.
These output properties are of type EventEmitter which allows the child component to emit custom
events. The parent component can listen to these events using event binding in the template. This enables
communication from the child component to the parent component.
Parent Component
TS
parentValue = 0;
handleValueChanged(newValue: number) {
console.log('Value changed in child component:', newValue);
this.parentValue = newValue;
}
html
<h2>Parent Component</h2>
<p>Parent Value: {{ parentValue }}</p>
<app-child [childValue]="parentValue"
(valueChanged)="handleValueChanged($event)"></app-child>
Child Component
TS---------
@Input() childValue: number = 0; // Initialize childValue with a default
value
@Output() valueChanged = new EventEmitter<number>();
increment() {
this.childValue++;
this.valueChanged.emit(this.childValue);
}
1
Advance Angular v.17
5. Input() / Output() Decorators
Html
<h2>Child Component</h2>
Explanation:
Parent Component (parent-component):
Initial Value: The parent component initializes a property parentValue to 0.
Input Provider: The parent component acts as the provider of input data. It passes the parentValue to the
child component through an input property.
Output Listener: The parent component listens to events emitted by the child component. Specifically, it
listens to the valueChanged event.
Summary
The parent component initializes the initial value (parentValue).
The parent component passes this value to the child component through an input property
(childValue).
2
Advance Angular v.17
5. Input() / Output() Decorators
The child component receives the initial value from the parent and updates it.
When the child component updates the value, it emits an event (valueChanged) to notify the
parent about the change.
The parent component listens to this event and updates its value accordingly.