Angular — Four Ways for Communication Between Components
Component is the basic building block of Angular applications. An Angular application is usually consisted of many separated components. In order to make them work together, we need communication between components. Here I would like to introduce four ways for communication between components that Angular developers should know.
1. Binding (@Input & @Output)
Data binding is the most basic way to communicate between components.
@Component({
selector: 'child',
...
})
export class ChildComponent {
@Input() counter: number = 0;
@Output() counterChange = new EventEmitter<number>();
onUpdateCounter() {
this.stateChange.emit(this.counter + 1);
}
}
To bind a value to the input:
<child [counter]="counter"></child>
To listen to the output:
<child (counterChange)="onCounterChange($event)"></child>
To establish a two-way binding:
<child [(counter)]="counter"></child>
Comparing with all other approaches for communication I am going to mention below, binding is the cleanest and simplest one. It is the most maintainable way for passing data. Hence, binding is always the most preferable way that…