DEV Community

Cover image for Angular Inter-Component Communication Pattern
John Peters
John Peters

Posted on • Updated on

Angular Inter-Component Communication Pattern

  • Set up output EventEmitters in our ButtonItemsComponent

   @Output() onBackEvent = new EventEmitter<any>();
   @Output() onEditEvent = new EventEmitter<any>();
   @Output() onSaveEvent = new EventEmitter<any>();
   @Output() onDeleteEvent = new EventEmitter<any>();
   @Output() onCloseEvent = new EventEmitter<any>();

Enter fullscreen mode Exit fullscreen mode
  • Hook up button click events to Event Emitters, getContent is used to include other content for the event.
onBackClicked(div) {
   this.onBackEvent.emit(this.getContent(div));
 }
 onEditClicked(div) {
   this.onEditEvent.emit(this.getContent(div));
 }
 onSaveClicked(div) {
   this.onSaveEvent.emit(this.getContent(div));
 }
 onDeleteClicked(div) {
   this.onDeleteEvent.emit(this.getContent(div));
 }
 onCloseClicked() {
   this.onCloseEvent.emit(this.model);
 }
Enter fullscreen mode Exit fullscreen mode
  • In other program containing the ButtonItemsComponent
 @ViewChild(ButtonItemsComponent)
   ButtonItemsComponent: ButtonItemsComponent;

// this follows in AfterViewInit

  this.ButtonItemsComponent
  .onBackEvent
  .subscribe((item) => {
    this.onGoBack();
 });
 this.ButtonItemsComponent
  .onCloseEvent
  .subscribe((item) => {
    //can do clean up here
  });
 this.ButtonItemsComponent
  .onDeleteEvent
  .subscribe((item) => {
   this.onDelete(item);
 });
 this.ButtonItemsComponent
  .onSaveEvent.subscribe((item) => {
  this.onSave(item);
 });
Enter fullscreen mode Exit fullscreen mode

Works as a one way from child to parent communication as shown, just reverse for parent to child.

JWP 2020

Top comments (0)