Understanding Input and Output Data Binding in Angular
One of the fundamental features of any modern front-end framework is the ability to bind data between the view (HTML) and the component class (TypeScript). In Angular, this is achieved using a set of directives known as "input" and "output" binding.
Input Binding
Input binding allows you to pass data from the component template (view) to the component class. It is denoted using the @Input
decorator. For example:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-user',
template: `
<p>Username: {{ username }}</p>
`
})
export class UserComponent {
@Input() username: string;
}
In this example, the username
property is decorated with the @Input
decorator, which means that it can be passed in from the parent component as an input binding. The parent component can then bind to this property using the [username]
attribute:
<app-user [username]="currentUsername"></app-user>
Here, the currentUsername
property of the parent component is being passed to the username
input of the UserComponent
.
Output Binding
Output binding allows you to pass data from the component class to the component template (view). It is denoted using the @Output
decorator and the EventEmitter
class. For example:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<button (click)="decrement()">-</button>
<span>{{ count }}</span>
<button (click)="increment()">+</button>
`
})
export class CounterComponent {
count = 0;
@Output() countChange = new EventEmitter<number>();
increment() {
this.count++;
this.countChange.emit(this.count);
}
decrement() {
this.count--;
this.countChange.emit(this.count);
}
}
In this example, the CounterComponent
has a count
property that is being displayed in the template. It also has two buttons that increment and decrement the count
when clicked. The @Output
decorator is used to define an countChange
event that is emitted whenever the count
changes.
The parent component can bind to this event using the (countChange)
syntax:
<app-counter (countChange)="onCountChange($event)"></app-counter>
Here, the onCountChange
method of the parent component will be called whenever the countChange
event is emitted by the CounterComponent
. The current value of count
will be passed to the parent component via the $event
variable.
I hope this article helps!