【问题标题】:How to set initial value for formArray?如何设置formArray的初始值?
【发布时间】:2020-06-18 17:06:24
【问题描述】:

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

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(''));
  }

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

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

    您可以在 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

    【讨论】:

    • 很好,但一个非常重要的想法非常......我的成分是字符串数组......?
    • 我也不能在初始化时调用它,因为我在改变下拉菜单时调用它,但它没有什么大问题
    • 对于字符串数组,您可以用字符串替换对象,它会正常工作。
    • 更改下拉菜单是什么意思??我没有得到这个。
    • 是的,我改为调用 onInit 我在 onChange..Example onChange(event) { this.allRecepies.map(obj => { if (obj.id == event.target.value) { this .selectedMeal = Object.assign(obj); console.log(this.form.value); } }) this.editCity(); }
    猜你喜欢
    • 2017-04-14
    • 2021-09-24
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 2021-07-10
    • 1970-01-01
    • 2021-01-15
    相关资源
    最近更新 更多