找不到路径控制:'成分 - > 0 - > 0'

时间:2018-05-17 15:45:22

标签: angular formarray

我正在尝试为配料构建一个表格,其中包含成分的嵌套动态输入。我不知道自己做错了什么。这是浏览器控制台的错误:

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 :(得分:0)

我在项目中遇到了类似的问题。就我而言,我没有为数组中的每种成分创建一个组。即数组直接包含对成分列表的引用。 为什么要在createIngredient()中分配数组?这可能会引起一些混乱。相反,我相信,您应该返回一个新的Ingredient对象,即this.formBuilder.group(new Ingredient('',0))。

基于reactive-forms文档,我对该项目的实现如下:

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));