We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Saturday, May 19, 2018

How to pass the data child component to parant component using EventEmitter in Angular

First, we know that what is EventEmitter in angular 2

EventEmitter is a class in an angular framework.  It has emit() method that emits custom events. We can use EventEmitter in custom event binding.
EventEmitter objects always accept any number of generic arguments. EventEmitter is an Angular2 abstraction and its only purpose is to emit the events in the components.

when any action performs within a child component, the child component fires an event that is traced by the parent component to an intimate parent component. The parent component can perform separate actions against that event to perform its own logical operations.

If the child component wants to send the information back to the parent component, it can raise an event with the help of @Output decorator. Like the @Input decorator, we can always use @Output decorator to decorate any property of the child component. This property must be an event of the child component. The data to pass is called the event payload. In Angular 2, an event is defined with an EventEmitter object. Below is the sample example of an output event emitter property.

@Output() click EventEmitter<string> = new EventEmitter<string>();


What is @Input() and @Output decorators

@Input()  Defines an input variable in component communication. It is used to communicate from parent to child component using property binding. 

@Output(): Defines an output variable in component communication. It is used to communicate from child to parent component using custom event binding.

Now we see the practice example 

First, we need to configure typescript and angular 2 in our visual studio so for this you can go this link

Now we will perform  our angular js application Let us see step by step

Step1

We create a typescript file and give the name app.component.parent.ts and write down the code given below.
import { ComponentOnInit } from '@angular/core';

@Component({
    moduleId : module.id,
    selector : 'my-app',
    templateUrl : 'app.component.parent.html',
})

export class ParentComponent implements OnInit {
    constructor() { }

    ngOnInit() { }

    confirmdetails(detailsstring): void {
        alert(details);  
    }  
} 

Step2

We create a typescript file and give the name app.component.child.ts and write down the code given below.

import { ComponentInputOutputEventEmitter } from '@angular/core';

@Component({
    selector : 'childevent',
    template: '<input  placeholder="{{name}}" #nametext/><br/><br/><input  placeholder="{{address}}" #addresstext/><br/><br/><input  placeholder="{{email}}" #emailtext/><button class="btnClass" (click)="registerDetails(nametext,addresstext,emailtext)">Click</button>',
    styles: [".btnClass {color:green;}"]
})

export class ChildComponent {
    @Input('placeholder'namestring = "Type your name..";
    @Input('placeholder'addressstring = "Type your address..";
    @Input('placeholder'emailstring = "Type your email..";
    @Output() employeeDetailsEventEmitter<string> = new EventEmitter<string>();

    registerDetails(txtName: { valuestring; }, txtAddress: { valuestring; }, txtEmail: { valuestring; }) {
        if (txtName.value == '') {
            alert('Enter your name.');

            return;
        }
        else if (txtAddress.value == '') {
            alert('Enter your address .');

        }
        else if (txtEmail.value == '') {
            alert('Enter your email ..');
        }
        else {
            this.employeeDetails.emit("Employee Name: " + txtName.value);
            this.employeeDetails.emit("Employee Address: " + txtAddress.value)
            this.employeeDetails.emit("Employee EmailId: " + txtEmail.value)
           
        }
    }
      
}

Step3

We create a typescript file and give the name app.module.ts and write down the code given below.

import { ComponentInputOutputEventEmitter } from '@angular/core';

@Component({
    selector : 'childevent',
    template: '<input  placeholder="{{name}}" #nametext/><br/><br/><input  placeholder="{{address}}" #addresstext/><br/><br/><input  placeholder="{{email}}" #emailtext/><button class="btnClass" (click)="registerDetails(nametext,addresstext,emailtext)">Click</button>',
    styles: [".btnClass {color:green;}"]
})

export class ChildComponent {
    @Input('placeholder'namestring = "Type your name..";
    @Input('placeholder'addressstring = "Type your address..";
    @Input('placeholder'emailstring = "Type your email..";
    @Output() employeeDetailsEventEmitter<string> = new EventEmitter<string>();

    registerDetails(txtName: { valuestring; }, txtAddress: { valuestring; }, txtEmail: { valuestring; }) {
        if (txtName.value == '') {
            alert('Enter your name.');

            return;
        }
        else if (txtAddress.value == '') {
            alert('Enter your address .');

        }
        else if (txtEmail.value == '') {
            alert('Enter your email ..');
        }
        else {
            this.employeeDetails.emit("Employee Name: " + txtName.value);
            this.employeeDetails.emit("Employee Address: " + txtAddress.value)
            this.employeeDetails.emit("Employee EmailId: " + txtEmail.value)
           
        }
    }
      
}


Step4

We create a typescript file and give the name app.component.parent.ts and write down the code given below. 
<div>
    <br />
    <h2>Employee details</h2>
    <childevent (employeeDetails)="confirmdetails($event,$event,$event)"></childevent><br />

</div 



Step5

we will go in index.html page and change some code as below given code

<!DOCTYPE html>
<html>
<head>
    <title>Angular QuickStart</title>
    <base href="/src/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="styles.css" rel="stylesheet" />
    <link href="../node_modules/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
    <!-- Polyfill(s) for older browsers -->
    <script src="../node_modules/jquery/dist/jquery.js"></script>
    <script src="../node_modules/bootstrap/dist/js/bootstrap.js"></script>
    <script src="../node_modules/core-js/client/shim.min.js"></script>
    <script src="../node_modules/zone.js/dist/zone.js"></script>
    <script src="../node_modules/systemjs/dist/system.src.js"></script>
    <script src="systemjs.config.js"></script>
    <script>
        System.import('main.js').catch(function (err) { console.error(err); });
    </script>
</head>
<body>
    <my-app>Please wait Angular application is loading ...</my-app>
</body>

</html>

Now see the output and when we will click the button without inserting anything then check the validation

After that fill all fields and click  then see the data one by one in alert


No comments: