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';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent,childComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
 
//app.component.ts
import { Component } from '@angular/core';
import {childComponent} from './child.Component';
@Component({
  selector: 'my-app',
  template: ` <div class="parent">
            <h1>Parent</h1>
            <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>
        </div>`,
        styles:[`.parent{ border:2px solid blue;}`]
})
export class AppComponent {
private childData:string;
 }

Child Component

 
//child.component.js
import { Component,EventEmitter } from '@angular/core';
@Component({
  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;}`],
        inputs:['parentValue'],
        outputs:['childEvent']

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

	this.childEvent.emit(value);
}
}

Leave a Reply

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