Saber Alex
Saber Alex

Reputation: 1723

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

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.

Upvotes: 4

Views: 6037

Answers (2)

Qortex
Qortex

Reputation: 7466

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.

Upvotes: 6

Aditya Vashishtha
Aditya Vashishtha

Reputation: 189

You can use the behavior subject observable for this,create one behavior subject in a service class and then emit data from patient-fields component and then subscribe this observable inside patient-analyser so that you will have the desired data you wanted.

This approach better than Input/Output property way because each input/output property changes triggers the change detection which is quite expensive operation in angular framework.

Upvotes: 0

Related Questions