@Input @Output decorators in Angular

This post helps you understand the usage of the decorators in Component communication

Pavan Chilukuri
Jan 18, 2019 · 3 min read
Image for post
Image for post

Decorator

Class Decorator

@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent {
title = ‘app’;
}

Class Field Decorator

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
@Input() count;
// code
}
Image for post
Image for post
Parent to Child & Child to Parent Components Communication

Parent to Child Communication, use @Input( )

<button (click)=”sendToChild()”>Send Chocolates to Child</button>
<app-child [chocolateCount]=”chocolate”></app-child>
export class ParentComponent { 
chocolate = 0;
sendToChild() {
this.chocolate++;
}
}
<p>Chocolates recieved from Parent — {{chocolateCount}}</p>
export class ChildComponent {
@Input() chocolateCount;
}

Child to Parent Communication, use @Output( )

<button (click)=’sayThanks($event)’>Say ‘Thank you’ to Parent</button>
export class ChildComponent {
@Output() thanks: EventEmitter<string> = new EventEmitter<string>();

sayThanks($event) {
this.thanks.emit('Thank you');
}
}
<app-child [chocolateCount]=”chocolate” (thanks)=”sayThanks($event)”></app-child>
export class ParentComponent {
chocolate = 0;
thankYouText = '';
sendToChild() {
this.chocolate++;
}
sayThanks(event) {
this.thankYouText = event;
}
}

Quick Links

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store