Home » Javascript » Add all the values from a FormArray to firebase using angular 6

Add all the values from a FormArray to firebase using angular 6

Posted by: admin October 18, 2018 Leave a comment

Questions:

So I am new to angular and firebase. When ever I try submitting the form It only saves the last value I input into the array. I am missing something but not sure what. When you input text and hit the + button it displays what you input in a list below the input field.Just need help saving all values to firebase.

    <form #f="ngForm" (ngSubmit)="save(f.value)">      
    <div class="form-group">
        <label for="ingredient">Ingredients</label>
        <div class="input-group mb-3">
          <input ngModel name="ingredients" id="ingredient" type="text" class="form-control" #ingredient>
          <div class="input-group-append">
            <button type="button" class="input-group-text fa fa-plus" (click)="addIngredient(ingredient)"></button>
          </div>
        </div>
          <ul class="list-group">
            <li
              *ngFor="let ingredient of ingredients.controls"
              (click)="removeIngredient(ingredient)"
              class="list-group-item">
              {{ ingredient.value }}
            </li>
          </ul>
      </div>
  <button class="btn btn-primary">Save</button>

</form>

Here is the TS file for the code

form = new FormGroup({
    ingredients: new FormArray([])
  });
save(recipe){
     //this.recipeService.create(recipe);
     console.log(recipe);     
   }



  addIngredient(ingredient: HTMLInputElement) {
    this.ingredients.push(new FormControl(ingredient.value));
    ingredient.value = '';
  }



  get ingredients() {
    return this.form.get('ingredients') as FormArray;
  }


  removeIngredient(ingredient: FormControl){
    let index = this.ingredients.controls.indexOf(ingredient);
    this.ingredients.removeAt(index);
  }
Answers: