Passing an Event from a child component to another child component Angular 7

Issue

I have two child components in my app component: patient-fields and patient-analyser.

The patient-fields contains forms and submit button while the patient-analyser need the data from the patient-field before it performs a POST request to get the patient’s data analysed.

My current solution is having EventEmitter from the patient-fields that trigger another eventEmmiter object in App. Then, I’ll pass the app’s event emitter to be subscribed by the patient-analyser as shown below:

patient-fields.component.ts (child1):


 @Output() toggleSubmit: EventEmitter<FormData> = new EventEmitter();

  onSubmit() {
    this.toggleSubmit.emit(this.patientFieldForm.value);
  }

patient-analyser.component.ts (child2):


  @Input() pf: EventEmitter<any>;
  constructor() { }

  ngOnInit() {
    this.pf.subscribe((data) => {
      // Performing a POST request to analyse the patient data
    });

app.component.ts (parent):


  @Output() pf: EventEmitter<any> = new EventEmitter();

  onSubmit(patientFields: FormData) {
    this.pf.emit(patientFields);
  }

app.component.html:


<app-patient-analyser
    [pf] = pf
  ></app-patient-analyser>

<app-patient-fields
    (toggleSubmit)="onSubmit($event)"
  ></app-patient-fields>


Is there a better solution for this?

Thanks before.

Solution

You should aim for reducing any dependency between components template codes. It will allow you to maximize reusability between your components.

With your current solution, you are forced to tightly couple your components template codes, which means if ever you modify or refactor one of them you are going to run into maintainability issues.

The better way to go is to use an inter-components communication service. The concept is very well explained here in the Angular docs.

Here, you should create a service that you inject in all components, where you host the event emitter, and thus you can subscribe/emit without coupling your template codes.

Answered By – Qortex

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published