Angular 6 : Component Communication using @Input, @Output and EventEmitter
Below example is implemented to communicate parent and child component using @Input, @Output and EventEmitter.
Model class
export class country{
ID : number;
Name : string;
}
parent.component.ts
import { Component, OnInit } from '@angular/core';
import { country } from 'src/app/Model/Country';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
name: string = "DemoName";
vmCountry: country;
receivedChildMessage: string;
receivedChildAnotherMessage: country;
constructor() { }
ngOnInit() {
this.vmCountry = new country();
this.receivedChildAnotherMessage = new country();
this.vmCountry.Name = "India";
}
getMessage(message: string) {
this.receivedChildMessage = message;
}
getAnotherMessage(varCountry : country) {
this.receivedChildAnotherMessage = varCountry;
}
}
<h1>
parent works! test
</h1>
<app-child [name]="name" [varCountry]="vmCountry"
(messageToEmit)="getMessage($event)"
(anotherMessageToEmit)="getAnotherMessage($event)"></app-child>
<div class="row">
<div class="col-md-2">
{{receivedChildMessage}}
</div>
<div class="col-md-2">
{{receivedChildAnotherMessage.Name}}
</div>
</div>
child.component.ts
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { country } from 'src/app/Model/Country';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() name: string;
@Input() varCountry: country;
@Output() messageToEmit = new EventEmitter<string>();
@Output() anotherMessageToEmit = new EventEmitter<country>();
constructor() { }
ngOnInit() {
}
sendMessageToParent(message: string) {
this.messageToEmit.emit(message)
}
sendAnotherMessageToParent() {
this.varCountry = new country;
this.varCountry.ID = 10;
this.varCountry.Name = "Japan";
this.anotherMessageToEmit.emit(this.varCountry)
}
}
child.component.html
<p>
child works {{name}}!
</p>
<h1>{{varCountry.Name}}</h1>
<div class="row">
<div class="col-md-2">
<button (click)="sendMessageToParent('message from child')">Send to Parent</button>
</div>
<div class="col-md-2">
<button (click)="sendAnotherMessageToParent()">Another Send to Parent </button>
</div>
</div>
app.module.ts
@NgModule({
declarations: [
ParentComponent,
ChildComponent,
.....
],
.....
})
Hope this will help you and save your time.
Enjoy !!!
:)