Angular Events
-
Parent child communication
-
parent.component.ts
- Trigger event in another component
- Button click
- Binding to keyboard events
Parent child communication
// child.component.ts
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent {
@Output() someEvent = new EventEmitter<string>();
// Function that triggers the event
triggerEvent() {
this.someEvent.emit();
}
}
parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
export class ParentComponent {
message: string;
receiveMessage($event) {
this.message = $event;
}
}
In the parent component template, we bind to the messageEvent
property of the child component
and call the receiveMessage()
method when the event is emitted.
<!-- parent.component.html -->
<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>{{message}}</p>
Trigger event in another component
Trigger component
import { Component, EventEmitter, Output } from '@angular/core';
export class ComponentABC {
@Output() theEmittedEvent = new EventEmitter<void>();
// Call this method when needed to trigger the event
eventTriggerMethod() {
this.triggerMethod.emit();
}
}
Listener component
import { Component, Input } from '@angular/core';
export class ComponentXYZ {
handleEvent() {
// Method to be called when the event is triggered
}
}
<app-abc (theEmittedEvent)="xyz.handleEvent()" ></app-abc>
<app-xyz #xyz></app-xyz>
Button click
<button (click)="login()" type="submit" class="btn primary">Login</button>
Binding to keyboard events
<input (keydown)="onKeydown($event)">
onKeydown(event: KeyboardEvent) {
console.log(event.key);
if (event.key === "Enter") {
// do something
}
}
HostListener decorator to bind to host (global) events
@HostListener('window:keydown', ['$event'])
private moves: any = {
ArrowLeft: () => 'ArrowLeft Pressed',
ArrowRight: () => 'ArrowRight Pressed',
ArrowDown: () => 'ArrowDown Pressed',
ArrowUp: () => 'ArrowUp Pressed',
};
onKeydown(event: KeyboardEvent): void {
if (this.moves[event.key]) {
console.log(this.moves[event.key]());
}
}