Sharing Data from Child to Parent Component in Angular

Send Data to Parent Component in Angular

https://speedteach.blogspot.com/2021/10/sharing-data-from-child-to-parent.html
Sharing Data from Child to Parent Component

In this blog, we learn how to child component pass data to parent component in Angular. 

In this previous blog, we looked at how to parent component can directly access properties and methods of the child component using Template Reference Variables.

The @Output() decorator in a child component or directive lets data flow from the child to the parent. @Output() lets the child send data to a parent component. The child component uses the @Output() property to raise an event to notify the parent of the change. To raise an event, an @Output() must have the type of EventEmitter, which is a class in @angular/core that you use to emit custom events.

Example:
app.component.ts
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent {
    showLoginForm: boolean = false;

    login() {
        this.showLoginForm = true;
    }

    cancelLoginForm() {
        this.showLoginForm = false;
    }
}

app.component.html
<button *ngIf="!showLoginForm" type="submit" (click)="login()">Login</button>

<!-- child component  -->
<app-child *ngIf="showLoginForm" (cancelLoginForm)="cancelLoginForm()"></app-child>

child.component.ts
import { Component, Input, OnInit, Output } from '@angular/core';
import { EventEmitter } from '@angular/core';

@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css']
})

export class ChildComponent {
    @Output() cancelLoginForm: EventEmitter<any> = new EventEmitter();

    cancel() {
        this.cancelLoginForm.emit();
    }
}

child.component.html
<form>
    <!-- name field  -->
    <label for="name">Name:</label>
    <input type="text" name="name">
    <br>

    <!-- password field  -->
    <label for="assword">Password:</label>
    <input type="password" name="password">
    <br>

    <!-- login button  -->
    <button type="submit">Submit</button>

    <!-- Cancel button  -->
    <button type="submit" (click)="cancel()">Cancel</button>
</form>

Output:


Reference

Comments