@input decorator used to pass data from parent to child component.
@Output decorator is used to pass the data from child to parent component.
@Output decorator binds a property of angular EventEmitter class type.
@input Example
child.component.ts
import { Component, OnInit, Input} from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
constructor() { }
@Input() myChildDataInputVariable: string;
ngOnInit(): void {
console.log(this.myChildDataInputVariable);
}
}
child.component.html
<p>child works!</p>
{{myChildDataInputVariable}}
app.component.ts (Parent)
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'myapp';
passingFromParent: string = "Data Passed from Parent to Child Component"
}
app.component.html
<div>
<app-child [myChildDataInputVariable]="passingFromParent" >
</app-child>
</div>
@output example
child.component.ts
import { Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
constructor() { }
@Input() myChildDataInputVariable: string;
@Output() passDataFromChildToParentOutput:EventEmitter<string>= new EventEmitter();
outputMessage:string="I am child component."
ngOnInit(): void {
console.log(this.myChildDataInputVariable);
}
passValues(){
this.passDataFromChildToParentOutput.emit(this.outputMessage);
}
}
child.component.ts
<p>child works!</p>
{{myChildDataInputVariable}}
<button (click)="passValues()"> Request Child Data </button>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'myapp';
name: string = "Ranjit";
passingFromParent: string = "Data Passed from Parent to Child Component"
RequestChildData(data:any){
console.log(data);
}
}
app.component.html
<div>
<app-child [myChildDataInputVariable]="passingFromParent" (passDataFromChildToParentOutput) ="RequestChildData($event)" >
</app-child>
</div>
Check our other Angular Tutorials at Angular Tutorials
References
- https://angular.io/guide/inputs-outputs
Learn more about Angular features in the next upcoming blog articles.
Happy Learning!