Невозможно найти элемент управления с путем: «ингредиенты -> 0 -> 0» - PullRequest
0 голосов
/ 17 мая 2018

Я пытаюсь создать форму для рецептов с вложенным динамическим вводом ингредиентов.Я не знаю, что я делаю не так.это ошибка консоли браузера:

Cannot find control with path: 'ingredients -> 0 -> 0'

это мой HTML

<div formArrayName="ingredients">
  <div *ngFor="let ingredient of recipeForm.get('ingredients')['controls']; let i=index" [formGroupName]="i">
    <!-- address header, show remove button when more than one address available -->
     <div>
      <span>Zutat {{i + 1}}</span>
      <!-- <span *ngIf="recipeForm.get('ingredients')['controls'].length > 1" (click)="removeIngredient(i)">
      </span> -->
    </div>

    <!-- Angular assigns array index as group name by default 0, 1, 2, ... -->
    <div [formGroupName]="i">
      <!--ingredient-->
      <div [formGroup]="ingredient">
        <div class="form-group col-xs-6">
          <input type="text" class="form-control" formControlName="newIngredient">
        </div>
        <div class="btn btn-success" (onclick)="addIngredient()">neue Zutat</div>
      </div>
    </div>
  </div>
</div>

, и это мой TS-файл

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validator, Validators } from '@angular/forms';
import { NewRecipe } from '../recipe.interface';
import { validateConfig } from '@angular/router/src/config';





@Component({
  selector: 'app-recipe-creator',
  templateUrl: './recipe-creator.component.html',
  styleUrls: ['./recipe-creator.component.css']
})
export class RecipeCreatorComponent implements OnInit {

  constructor(private formBuilder: FormBuilder) {}
  recipeForm: FormGroup;
  ingredients: FormArray;
  instructions: FormArray;

  ngOnInit() {
    this.recipeForm = this.formBuilder.group({
      name: '',
      category: '',
      prep_time: 0,
      cooking_time: 0,
      price: 0,
      ingredients: this.formBuilder.array([this.createIngredient()]),
      instructions: this.formBuilder.array([this.createInstruction()])
    });
  }
  createIngredient(): FormGroup {
    return this.formBuilder.group({
      newIngredient: ['']
    });
  }
  createInstruction(): FormGroup {
    return this.formBuilder.group({
      newInstruction: ['']
    });
  }
  addIngredient(): void {
    this.ingredients = this.recipeForm.get('ingredient') as FormArray;
    this.ingredients.push(this.createIngredient());
  }
  addInstruction(): void {
    this.instructions = this.recipeForm.get('instruction') as FormArray;
    this.instructions.push(this.createInstruction());
  }
  saveRecipe() {}
  removeIngredient(i) {}
}

Ядовольно плохо знаком с угловой, и это сводит меня с ума.Обучающие программы по всем формам содержат код, который, похоже, не поддерживается Angular 6. Существует ли более новое учебное пособие о вложенных формах с FormArray где-нибудь?

Заранее спасибо.

1 Ответ

0 голосов
/ 28 июня 2018

Я столкнулся с подобной проблемой в моем проекте. В моем случае я не создал группу для каждого ингредиента в массиве. то есть массив непосредственно содержал ссылки на список ингредиентов. Почему вы назначаете массив в createIngredient ()? Это может вызвать некоторую путаницу. Вместо этого я считаю, что вы должны вернуть новый объект Ingredient, то есть this.formBuilder.group (new Ingredient ('', 0)).

Основываясь на документации реактивных форм , моя реализация этого проекта выглядит следующим образом:

export class RecipeEditComponent implements OnInit {
  id: number;
  editMode = false;
  recipeForm: FormGroup;

  constructor(private route: ActivatedRoute, private fb: FormBuilder, private recipeService: RecipeService) { }

  ngOnInit() {
    this.route.params.subscribe((p) => {
      console.log(p['id']);
      if(p['id'] !== undefined){
        this.editMode = true;
        this.id = Number(p['id']);
      }
      console.log('new mode: ' + !this.editMode);
    });

    this.recipeForm = this.fb.group({
      name: '',
      imageUrl: '',
      description: '',
      ingredients: this.fb.array([]),
    });

    if(this.editMode){
      const recipe = this.recipeService.getRecipeById(this.id);
      const ingsTemp = recipe.ingredients.map(ip => this.fb.group(ip));
      const ingredientsFormsArray = this.fb.array(ingsTemp);
      this.recipeForm.setControl('ingredients', ingredientsFormsArray);
      this.recipeForm.patchValue({
        name: recipe.name,
        imageUrl: recipe.imagePath,
        description: recipe.description,
      });
      console.log(ingredientsFormsArray);
      console.log(this.ingredients);
    }
  }

  onSubmit() {
    console.log(this.recipeForm.get('ingredients'));

  }

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

и в шаблоне

<div formArrayName="ingredients">
    <div *ngFor="let ingredient of ingredients.controls; let i = index" [formGroupName]="i">
        <div class="row">
          <div class="col-12">
            <div class="row">
              <div class="col-8">
                <div class="form-group">
                  <input type="text" class="form-control" formControlName="name">
                </div>
              </div>
              <div class="col-2">
                <div class="form-group">
                  <input type="number" class="form-control" formControlName="amount">
                </div>
              </div>
              <div class="col-2">
                <div class="form-group">
                  <button type="button" class="btn btn-danger">X</button>
                </div>
              </div>
            </div>
          </div>
        </div>
    </div>
  </div>

В моем случае я пропустил следующий шаг:

const ingsTemp = recipe.ingredients.map(ip => this.fb.group(ip));
...