@Input and @Output in Angular with the example
@Input Example
@Input and @output are used to make communication between components in angular, @input is used whenever we want to transfer data from parent component to child component and @ output is used when we want some data from child component to Parent component.
- First We create and child component “inputex” and write following code into ts and html file .
import { Component, OnInit, Input, OnChanges } from '@angular/core'; @Component({ selector: 'app-inputex', templateUrl: './inputex.component.html', styles: [] }) export class InputexComponent implements OnChanges{ // firstvar and secondvar are reference alias name of input properties , which are used in parent component @Input('firstvar') firstvar; @Input('secondvar') second; getfirst: string; getsecond: string; constructor() { } // We are using ngOnChanges because input property will be updated ngOnChanges() { this.getfirst = this.firstvar; this.getsecond = this.second; } }
<p> inputex works! </p> <h2>First Value is : {{ getfirst }}</h2> <h2>Second Value is : {{ getsecond }}</h2>
Step 2: Parent Component (app.component)
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <input type="text" #txt1 /><input type="button" value="click here" (click)="setvalue(txt1.value)" /> <app-inputex [firstvar]="firstvarvalue" [secondvar]="5+5" ></app-inputex> `, styles:[` h1 { background-color: red; } `] }) export class AppComponent { firstvarvalue : string; setvalue(myvalue) { this.firstvarvalue = myvalue; } }
Output:
@Output Example
Child Component
import { Component, OnInit, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-inputex', templateUrl: './inputex.component.html', styles: [] }) export class InputexComponent implements OnInit{ @Output() sendvalue =new EventEmitter(); @Output('refvar') secondvalue = new EventEmitter(); constructor() { } ngOnInit() { this.sendvalue.emit('This is Child Component value'); } sendvaluefun(data) { this.secondvalue.emit(data); } }
<p> inputex works! </p> <input type="text" #txt1 /> <input type="button" value="Click Here to Send" (click)="sendvaluefun(txt1.value)" />
Parent Component
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <app-inputex (sendvalue)="myfunction($event)" (refvar)="secondfun($event)"></app-inputex> <span>First Value is : {{ myvalue }}</span> <span>Second Value is : {{ second }}</span> `, styles:[` h1 { background-color: red; } `] }) export class AppComponent { myvalue: string; second: string; myfunction(ev) { this.myvalue = ev; } secondfun(data) { this.second = data; } }
Output
good example to implement parent and child relationship…thank you
hello