Let's say I have a pair of parent-child components in Angular as follows:
Child component class:
export class ChildComponent {
@Input() addTask:any;
}
Child component template:
<button (click)="addTask('cleaning')">Add Task</button>
Parent component class:
export class ParentComponent {
newTask:string;
add(task:string){
this.newTask = task;
}
}
Parent component template:
<div>
<app-child [addTask]="add.bind(this)"></app-child>
</div>
Here, I am passing a string from the child to the parent by passing the parent method to the child using property binding. I have read that this is okay as long as the method is not having side-effects. Let's assume my method is not having any side-effects.
But my question is, how is it different from using @Output() and EventEmitter?
The above functionality can be re-written using @Output() and EventEmitter as follows:
Child component class:
export class ChildComponent {
@Output() newEvent = new EventEmitter<string>();
addTask(task:string){
this.newEvent.emit(task);
}
}
Child component template:
<button (click)="addTask('cleaning')">Add Task</button>
Parent component class:
export class ParentComponent {
newTask:string;
add(task:string){
this.newTask = task;
}
}
Parent component template:
<div>
<app-child (newEvent)="add($event)"></app-child>
</div>
Both these approaches do the same thing. Please let me know what is the difference between these two approaches assuming my method is not having any side effects. Also I want to know which is the better approach and why.
In Angular, passing a method in property binding allows a component to pass a reference to a method defined in its parent component to one of its child components. This can be done using the square bracket syntax in the parent template and a corresponding input property in the child component class.
On the other hand, @Output() and EventEmitter in Angular provide a way for a child component to emit events to its parent component. This can be done by defining an event property in the child component class using the @Output() decorator, and emitting events using the EventEmitter class.
The main difference between these two approaches is that property binding with a method reference is a one-way communication from parent to child, whereas @Output() and EventEmitter provide a way for child components to emit events to their parent components. This makes @Output() and EventEmitter a more flexible and powerful mechanism for handling events in Angular applications, as it allows for bidirectional communication between components.