20
loading...
This website collects cookies to deliver better user experience
<div>
<h1>Parent component</h1>
<angular-child></angular-child>
</div>
<div>
Child Input: <input type="text" />
</div>
keydown
event that is emitted by the <input />
element above.<div>
Child Input: <input type="text" (keydown)="handleKeydown($event)" />
<p>Result from child component: {{ text }}</p>
</div>
import { Component, EventEmitter, Output } from "@angular/core";
@Component({
selector: "angular-child",
templateUrl: "./child.component.html",
styles: ["div { background-color: red }"]
})
export class ChildComponent {
@Output()
keyAction: EventEmitter<KeyboardEvent> = new EventEmitter<KeyboardEvent>();
text = "";
handleKeydown(event: KeyboardEvent): void {
this.text = event.key;
this.keyAction.emit(event);
}
}
KeyboardEvent
on a (keydown)
event in which the text is saved to a variable and it uses an EventEmitter
marked with an @Output()
decorator. (so that we can later catch it in the parent)<div>
<h1>Parent component</h1>
<angular-child (keyAction)="handleKeyAction($event)"></angular-child>
<p>Result from parent component: {{ keyPressed }}</p>
</div>
import { Component } from "@angular/core";
@Component({
selector: "angular-parent",
templateUrl: "./parent.component.html",
styleUrls: ["./parent.component.css"]
})
export class ParentComponent {
keyPressed = "";
handleKeyAction(event: KeyboardEvent): void {
this.keyPressed = event.key + " from Parent";
}
}