Cacoon
Cacoon

Reputation: 2538

Sending an array from a child component to a parent

I am writing a recipe web app, I have recipes that all hold an array of ingredients, and this is how I wrote my application

<h2>Add {{addRecipeForm.controls.name.value}}</h2>
<form [formGroup]="addRecipeForm">
  <label>Name:</label>
  <input type="text" formControlName="name" >
  <p *ngIf="addRecipeForm.controls.name.errors">This field is required!</p><p></p>
  <label>Serves:</label>
  <input type="text" formControlName="serves" >
  <p></p>
  <label>Steps:</label>
  <textarea  name="Text1" cols="60" rows="5" type="text" formControlName="steps" ></textarea>
  <p></p>
  <label>Remarks:</label>
  <textarea  name="Text1" cols="60" rows="3" type="text" formControlName="remarks" ></textarea>
  <p></p>
  <hr>
  <app-add-ingredient></app-add-ingredient>
  <hr>
  <button type="submit">Add new recipe</button> <button (click)="goBack()">Back</button>
</form>

I call to show the ingredient adder/lister, how do I send the array the add-ingredient component builds back up to its parent the add-recipe component, I looked into eventemitter but as stated here: What is the proper use of an EventEmitter? it doesnt seem to be a good idea? or atleast not ideal.

If eventemitter is not the best way to pass an array to its parent, what is? a service or some other way?

I have also read the official doc on this sort of thing found here https://angular.io/guide/component-interaction#!#parent-to-child-local-var but im not sure how to feed an array back to a parent after its been created (inputted via a form by the user) back

Upvotes: 1

Views: 81

Answers (1)

sheplu
sheplu

Reputation: 2975

the best solution would be to use a service only accessible with the two component.

You will find some examples on the angular doc https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

Upvotes: 3

Related Questions