如何设置formArray的初始值?

时间:2020-06-18 17:06:24

标签: javascript html angular typescript

我需要为表单设置初始值formArray f0r。 检查我的代码:

HTML:

            <div class="form-row form-group ingredients-drop">
                <button class="button" (click)="addAlias()">Add ingredients</button>
                <label>Kolicina</label>
                <div *ngFor="let ingredient of ingredients.controls; let i=index">
                    <input class="select add-ingredients" type="text" [formControlName]="i">
                </div>
            </div>

TS:

  allRecepies: any[] = [];
  selectedMeal: any
  form: FormGroup;


  ngOnInit() {
    this.getAllRecepies();
  }
  onChange(event) {
    this.allRecepies.map(obj => {
      if (obj.id == event.target.value) {
        this.selectedMeal = Object.assign(obj);
        console.log(this.form.value);
      }
    })
    this.editCity();
  }
  getAllRecepies() {
    this.mealService.getRecepies().subscribe(
      data => {
        this.allRecepies = data;
      }
    )
  } 

  editCity() {
    this.form.patchValue({
      name: this.selectedMeal.name ? this.selectedMeal.name : null,
      description: this.selectedMeal.description ? this.selectedMeal.description : null,
      preparationTime: this.selectedMeal.preparationTime ? this.selectedMeal.preparationTime : null,
      pictureUrl: this.selectedMeal.pictureUrl ? this.selectedMeal.pictureUrl : null,
      ingredients: this.selectedMeal.ingredients ? this.addMealArr() : null
    }) 
  } 
  addMealArr() {
    if(this.selectedMeal) {
     let a = this.selectedMeal.ingredients.map(obj => { return obj });
     return a;
    }
  }

  createForm() {
    this.form = this.formBuilder.group({
      name: [null],
      description: [null],
      preparationTime: [null],
      pictureUrl: [''],
      ingredients: this.formBuilder.array([
        this.formBuilder.control(this.addMealArr())
      ])
    });
  }

  get ingredients() {
    return this.form.get('ingredients') as FormArray;
  }
  addAlias() {
    this.ingredients.push(this.formBuilder.control(''));
  }

这可能是不好的做法,但是我需要针对问题或堆叠闪电的教程,或者有人可以帮助我吗? 如果可能,我需要使用patchValue设置初始值? 还是使用另一种方法? 我不知道只是给我发送教程,更改代码或设置stackblitz吗? 我需要设置初始值并添加新行或删除现有行。

1 个答案:

答案 0 :(得分:0)

嘿,您可以在FormGroup中设置如下初始值:

recipes = [
    {
        ingredients: [
            {name: 'Grapes', amount: 12},
            {name: 'Potato', amount: 12}
        ]
    },
    { 
        ingredients: [
            {name: 'Banana', amount: 12},
            {name: 'Orange', amount: 12}
        ]
    }
];
let recipeIngredients = new FormArray([]);
const recipe = this.recipes[0];

if (recipe["ingredients"]) {
    for (let ingredient of recipe.ingredients) {
    recipeIngredients.push(
        new FormGroup({
        name: new FormControl(ingredient.name, Validators.required),
        amount: new FormControl(ingredient.amount, [Validators.required])
        })
    );
    }
}
this.recipeForm = new FormGroup({
    ingredients: recipeIngredients
});

我为相同的示例创建了工作中的stackblitz示例 demo