Welcome back to CodeYourCraft! Today, we're diving into EventEmitter, an essential concept in Angular. We'll explore how to use it, why it's crucial, and see practical examples to help you grasp it better.
EventEmitter is a powerful tool in Angular that allows components to communicate with each other. By emitting and catching events, components can interact dynamically and respond to changes in real-time.
To create an EventEmitter, we'll use the @Output() decorator in Angular. Here's a simple example of a component that emits an event:
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponentComponent {
@Output() myEvent = new EventEmitter();
fireEvent() {
this.myEvent.emit();
}
}In this example, myEvent is an instance of EventEmitter. When the fireEvent() method is called, it emits the event.
To catch an event, we use the @Input() decorator and ngOnChanges() lifecycle hook in the receiving component. Here's how you can do it:
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-my-receiver',
templateUrl: './my-receiver.component.html',
styleUrls: ['./my-receiver.component.scss']
})
export class MyReceiverComponent implements OnInit {
@Input() receivedEvent: Event;
ngOnInit() {
this.receivedEvent.addListener(() => {
console.log('An event was received!');
});
}
}In this example, myReceiverComponent listens for the myEvent event emitted by myComponent.
Let's consider a simple parent-child communication scenario:
ParentComponent emits an event when a button is clicked.ChildComponent catches the event and performs an action.// ParentComponent
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<button (click)="fireEvent()">Click me</button>
`,
styleUrls: ['./parent.component.scss']
})
export class ParentComponent {
@Output() childAction = new EventEmitter();
fireEvent() {
this.childAction.emit();
}
}// ChildComponent
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<p>Child Component</p>
`,
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
@Input() receivedEvent: Event;
ngOnInit() {
this.receivedEvent.addListener(() => {
console.log('Child Component received an event!');
});
}
}When the parent's button is clicked, the child component receives the event and logs a message in the console.
What is EventEmitter used for in Angular?
That's all for today! In the next lesson, we'll dive deeper into EventEmitter, explore advanced techniques, and see more practical examples. Stay tuned and happy learning! 🎉