简体   繁体   English

如何在现有 formArray 上添加新行? Angular

[英]How to add new row on existing formArray ? Angular

On this form I need to add new row and remove row?在此表单上,我需要添加新行并删除行吗? How to do怎么做

  editCity() {   
    this.form = this.fo'',))),
      recepieType:
  } 

 createForm() {

this.form = this.formBuilder.group({
});

} }

I need to add function which is add new row or delete existing row.我需要添加 function 这是添加新行或删除现有行。

Here is the method to add ingredient:下面是添加成分的方法:

addIngredients() {
    let ingredientsCtrl = <FormArray> this.form.controls['ingredients']
    ingredientsCtrl.push(this.fb.group({ing: [null]}));
}

You can delete the ingredient(formGorup) using array index of the object您可以使用 object 的数组索引删除成分(formGorup)

Here is the method to delete ingredient:以下是删除成分的方法:

deleteIngredients(index: number) {
    let ingredientsCtrl = <FormArray> this.form.controls['ingredients']
    ingredientsCtrl.removeAt(index);
}

I recently implemented with a simpler and neat code:我最近用一个更简单整洁的代码实现了:

HTML: HTML:

<div>
    <input *ngFor="let field of fieldArray; let i = index;" type="text" [(ngModel)]="fieldArray[i]"  >
</div>

TS: TS:

fieldArray: Array<string> = [];
newAttribute: string = "";


addMoreRows(type:string){

        this.fieldArray.push(this.newAttribute);
        this.newAttribute = "";


    }

***Your formArray is fieldArray here. ***您的 formArray 在这里是 fieldArray。 This might not be the exact code you need, but off course you can take the lead from here, if helpful.这可能不是您需要的确切代码,但如果有帮助,您当然可以从这里带头。

I didnt use form builder etc. stuff.我没有使用表单生成器等东西。 newAttribute is just an empty filler placeholder. newAttribute 只是一个空的填充占位符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM