loading...
Cover image for An Angular Inter-Component Communication Pattern

An Angular Inter-Component Communication Pattern

jwp profile image John Peters ・1 min read
  • 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>();

  • 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);
 }
  • 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);
 });

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

JWP 2020

Posted on by:

jwp profile

John Peters

@jwp

Will Lit-Html rule the world?

Discussion

markdown guide