Angular Components: Pass data from child to parent

1 min read
Parent Component
parent.component.ts
export class ParentComponent {
msgFromChild = '';
recieveMessageFromChild(msg: string) {
this.msgFromChild = msg;
}
}
parent.component.html
<p>Message from child component: {{ msgFromChild }}</p>
<app-child (childEmitter)="recieveMessageFromChild($event)" />
Child Component
child.component.ts
import { Component, EventEmitter, Output } from '@angular/core';
export class ChildComponent {
@Output() childEmitter = new EventEmitter<string>();
msgToParent = '';
sendMessageToParent() {
this.msgToParent = 'Hello from the CHILD component';
this.childEmitter.emit(this.msgToParent);
}
}
child.component.html
<button (click)="sendMessageToParent()">Send message to PARENT component</button>
0
Subscribe to my newsletter
Read articles from sourcetrooper directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
