Input and Output in Angular2

We can easily pass data within component but when we want to transfer data in another component Let’s say from parent to child or child to parent we have to use Input and Output for passing data from parent to children we will use input and when we want to pass data from child to parent we will use Output. First add the

// app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import {childComponent} from './child.Component';

  imports:      [ BrowserModule ],
  declarations: [ AppComponent,childComponent ],
  bootstrap:    [ AppComponent ]
export class AppModule { }
import { Component } from '@angular/core';
import {childComponent} from './child.Component';
  selector: 'my-app',
  template: ` <div class="parent">
            <p>Value entered in child component {{childData}}</p>
            <input type="text" #parentText (keyup)="0"><br>
           <div class="child">
            <child (childEvent)="childData=$event" [parentValue]="parentText.value"></child></div>
        styles:[`.parent{ border:2px solid blue;}`]
export class AppComponent {
private childData:string;

Child Component

import { Component,EventEmitter } from '@angular/core';
  selector: 'child',
  template: ` <div class="children"><h2>Child</h2>
        <p>Value entered in parent component {{parentValue}}</p>
        <input type="text" #childText (keyup)="onChange(childText.value)"></div>`,
        styles:[`.children{ border:1px solid red;}`],

export class childComponent { 
public parentValue:string;
childEvent = new EventEmitter<string>()


Leave a Reply

Your email address will not be published. Required fields are marked *