Angular 6 : Component Communication using @Input, @Output and EventEmitter


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 { ComponentOnInit } 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 { 
  namestring = "DemoName";  
  vmCountrycountry
  receivedChildMessagestring;  
  receivedChildAnotherMessagecountry;
  constructor() { }
  ngOnInit() {
    this.vmCountry = new country();
    this.receivedChildAnotherMessage = new country();
    this.vmCountry.Name = "India"
  }
  
  getMessage(messagestring) {
    this.receivedChildMessage = message
  }
  getAnotherMessage(varCountry : country) { 
    this.receivedChildAnotherMessage = varCountry
  } 
}

parent.component.html
<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 { ComponentOnInitInputEventEmitterOutput } 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() namestring;
  @Input() varCountrycountry;
  @Output() messageToEmit = new EventEmitter<string>();
  @Output() anotherMessageToEmit = new EventEmitter<country>();
  
  constructor() { }
  ngOnInit() {
    
  }
  sendMessageToParent(messagestring) {
    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 !!!

:)

No comments:

Post a Comment