Components Communications
Written By: Avinash Malhotra
Updated on
Angular Components can communicate to each other to share data like Array, Objects, String, Number, html etc.
Two or more Component can communicate to each other using services.
Parent and child component can communicate to each other using @Input or @Output. A child component is a component used inside parent component. Any component used inside app-component
is its child component.
@Input
@Input decorator is used to pass data from parent to child component. It is used in child component. Create a child component named child
using ng g c server
.
Create child component
ng g c child
/* app.component.ts */
import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ChildComponent } from './child/child.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet,FormsModule,CommonModule,ChildComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent{
title = 'myApp';
message="hello child";
}
/* child.component.ts */
import { Component, Input} from '@angular/core';
@Component({
selector: 'app-child',
standalone: true,
imports: [],
templateUrl: './child.component.html',
styleUrl: './child.component.css'
})
export class childComponent{
@Input() greet="";
}
/* app.component.html */
<h1>{{title}}</h1>
<app-child [greet]="message"></app-child>
/* child.component.html */
<p>{{message}}</p>
@Output
@Output decorator is used to emit event from child component to parent component. We also need to use EventEmitter for @Output.
/* app.component.ts */
import { Component, Output } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ChildComponent } from './child/child.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet,FormsModule,CommonModule,ChildComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent{
title = 'myApp';
x=0;
showVal(count:number){
console.log(count);
this.x=count;
}
}
/* app.component.html */
<h1>{{title}}</h1>
<p>{{x}}</p>
<app-child (changeValue)="showVal($event)"></app-child>
/* child.component.ts */
import { Component, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-child',
standalone: true,
imports: [],
templateUrl: './child.component.html',
styleUrl: './child.component.css'
})
export class childComponent{
@Output() changeValue=new EventEmitter<number>();
counter=0;
changedValue(){
this.counter=this.counter+1;
this.changeValue.emit(this.counter);
}
}
/* child.component.html */
<h2>Child Component!</h2>
<button (click)="changedValue($event)">Click</button>
<p>{{counter}}</p>