angular 2删除formarray中的所有项目

问题描述 投票:46回答:7

我在formbuilder中有一个表单数组,我正在动态更改表单,即从应用程序1等单击加载数据。

我遇到的问题是所有数据都加载但是formarray中的数据保持不变,只是用旧的方式将旧项目连接起来。

如何清除formarray只有新项目。

我试过这个

const control2 = <FormArray>this.registerForm.controls['other_Partners'];
        control2.setValue([]);

但它不起作用。

有任何想法吗?谢谢

在炎热

ngOnInit(): void {
this.route.params.subscribe(params => { alert(params['id']);
            if (params['id']) {
                this.id = Number.parseInt(params['id']);
            }
            else { this.id = null;}
          });
if (this.id != null && this.id != NaN) {
            alert(this.id);
            this.editApplication();
            this.getApplication(this.id);
        }
        else
        {
            this.newApplication();
        }

}

onSelect(Editedapplication: Application) {
 this.router.navigate(['/apply', Editedapplication.id]);
}

editApplication() {
      
        this.registerForm = this.formBuilder.group({
              id: null,
            type_of_proposal: ['', Validators.required],
            title: ['', [Validators.required, Validators.minLength(5)]],
            lead_teaching_fellow: ['', [Validators.required, Validators.minLength(5)]],
            description: ['', [Validators.required, Validators.minLength(5)]],
            status: '',
            userID: JSON.parse(localStorage.getItem('currentUser')).username,
            contactEmail: JSON.parse(localStorage.getItem('currentUser')).email,
            forename: JSON.parse(localStorage.getItem('currentUser')).firstname,
            surname: JSON.parse(localStorage.getItem('currentUser')).surname,
            line_manager_discussion: true,
            document_url: '',
            keywords: ['', [Validators.required, Validators.minLength(5)]],
            financial_Details: this.formBuilder.group({
                  id: null,
                buying_expertise_description: ['', [Validators.required, Validators.minLength(2)]],
                buying_expertise_cost: ['', [Validators.required]],
                buying_out_teaching_fellow_cost: ['', [Validators.required]],
                buying_out_teaching_fellow_desc: ['', [Validators.required, Validators.minLength(2)]],
                travel_desc: ['', [Validators.required, Validators.minLength(2)]],
                travel_cost: ['', [Validators.required]],
                conference_details_desc: ['', [Validators.required, Validators.minLength(2)]],
                conference_details_cost: ['', [Validators.required]],
            }),

            partners: this.formBuilder.array
                (
                [
                    //this.initEditPartner(),
                    //this.initEditPartner()
                    // this.initMultiplePartners(1)
                ]
                ),
            other_Partners: this.formBuilder.array([
                //this.initEditOther_Partners(),
            ])
           
        });
       
    }

getApplication(id)
    {
        

        this.applicationService.getAppById(id, JSON.parse(localStorage.getItem('currentUser')).username)
            .subscribe(Response => {
               
                    if (Response.json() == false) {
                        this.router.navigateByUrl('/');
                    }
                    else {
                        this.application = Response.json();  
                          for (var i = 0; i < this.application.partners.length;i++)
                          {
                                this.addPartner();
                          }
                          for (var i = 0; i < this.application.other_Partners.length; i++) {
                              this.addOther_Partner();
                          }

                          this.getDisabledStatus(Response.json().status);
                        (<FormGroup>this.registerForm)
                            .setValue(Response.json(), { onlySelf: true }); 
                      }

                }
         
        );

       
        
        

       
    }

点击时不会调用ngonitit

angular angular2-forms
7个回答
95
投票

我有同样的问题。有两种方法可以解决这个问题。

Preserve subscription

您可以通过在循环中调用removeAt(i)函数来手动清除每个FormArray元素。

clearFormArray = (formArray: FormArray) => {
  while (formArray.length !== 0) {
    formArray.removeAt(0)
  }
}

这种方法的优点是你的formArray上的任何订阅,例如在formArray.valueChanges注册的订阅,都不会丢失。

有关更多信息,请参阅FormArray documentation


Cleaner method (but breaks subscription references)

您可以用新的FormArray替换整个FormArray。

clearFormArray = (formArray: FormArray) => {
  formArray = this.formBuilder.array([]);
}

如果您订阅了formArray.valueChanges observable,这种方法会导致问题!如果使用新数组替换FromArray,则将丢失对您订阅的observable的引用。


0
投票

为了保持代码清洁,我为使用Angular 7及以下版本的任何人创建了以下扩展方法。这也可用于扩展Reactive Forms的任何其他功能。

import { FormArray } from '@angular/forms';

declare module '@angular/forms/src/model' {
  interface FormArray {
    clearArray: () => FormArray;
  }
}

FormArray.prototype.clearArray = function () {
  const _self = this as FormArray;
  _self.controls = [];
  _self.setValue([]);
  _self.updateValueAndValidity();
  return _self;
}


0
投票

Angular 8

只需在formArrays上使用clear()方法:

(this.invoiceForm.controls['other_Partners']).clear();

22
投票

或者您可以简单地清除控件

this.myForm= {
     name: new FormControl(""),
     desc: new FormControl(""),
     arr: new FormArray([])
}

添加一些array

const arr = <FormArray>this.myForm.controls.arr;
arr.push(new FormControl("X"));

清除阵列

const arr = <FormArray>this.myForm.controls.arr;
arr.controls = [];

当您选择并清除多个选项时,有时它不会更新视图。解决方法是添加

arr.removeAt(0)

UPDATE

使用表单数组的更优雅的解决方案是在类的顶部使用getter,然后您可以访问它。

get inFormArray(): FormArray {
    this.myForm.get('inFormArray') as FormArray;
}

并在模板中使用它

<div *ngFor="let c of inFormArray; let i = index;" [formGroup]="i">
other tags...
</div>

重启:

inFormArray.reset();

推:

inFormArray.push(new FormGroup({}));

删除索引处的值:1

inFormArray.removeAt(1);

7
投票

Angular v4.4如果你需要保存对FormArray实例的相同引用,试试这个:

purgeForm(form: FormArray) {
  while (0 !== form.length) {
    form.removeAt(0);
  }
}

6
投票

从Angular 8+开始,您可以使用clear()删除FormArray中的所有控件:

const arr = new FormArray([
   new FormControl(),
   new FormControl()
]);
console.log(arr.length);  // 2

arr.clear();
console.log(arr.length);  // 0

对于以前的版本,推荐的方法是:

while (arr.length) {
   arr.removeAt(0);
}

https://angular.io/api/forms/FormArray#clear


5
投票

警告!

Angular v6.1.7 FormArray documentation说:

若要更改数组中的控件,请使用FormArray本身中的push,insert或removeAt方法。这些方法可确保在窗体的层次结构中正确跟踪控件。不要修改用于直接实例化FormArray的AbstractControls数组,因为这会导致奇怪和意外的行为,例如破坏的更改检测。

如果您直接在splice阵列上使用controls函数作为建议的答案之一,请记住这一点。

使用removeAt函数。

  while (formArray.length !== 0) {
    formArray.removeAt(0)
  }

3
投票

如果您要替换数组中的信息的数据结构与已经存在的匹配,您可以使用patchValue

https://angular.io/docs/ts/latest/api/forms/index/FormArray-class.html#!#reset-anchor

patchValue(value:any [],{onlySelf,emitEvent}?:{onlySelf?:boolean,emitEvent?:boolean}):void修补FormArray的值。它接受一个与控件结构匹配的数组,并尽力将值与组中正确的控件匹配。

它接受数组的超集和子集而不会抛出错误。

const arr = new FormArray([
   new FormControl(),
   new FormControl()
]);
console.log(arr.value);   // [null, null]
arr.patchValue(['Nancy']);
console.log(arr.value);   // ['Nancy', null]

或者你可以使用reset

reset(value?:any,{onlySelf,emitEvent}?:{onlySelf?:boolean,emitEvent?:boolean}):void重置FormArray。这意味着默认情况下:

数组和所有后代都标记为pristine数组和所有后代都标记为未触及所有后代的值将为null或null map您还可以通过传入与控件结构匹配的状态数组来重置为特定的表单状态。状态可以是具有值和禁用状态的独立值或表单状态对象。

this.arr.reset(['name', 'last name']);
console.log(this.arr.value);  // ['name', 'last name']

要么

this.arr.reset([   {value: 'name', disabled: true},   'last' ]);
console.log(this.arr.value);  // ['name', 'last name']
console.log(this.arr.get(0).status);  // 'DISABLED'

Here's是我早期工作中的一个分叉的Plunker演示,演示了每个的非常简单的利用。


2
投票

更新:Angular 8终于得到了清除Array FormArray.clear()的方法


0
投票

如果数组有100个项目,循环将需要很长时间才能删除所有项目。您可以清空FormArray的控件和值属性,如下所示。

clearFormArray =(formArray:FormArray)=> {formArray.controls = []; formArray.setValue([]); }


0
投票

在最新版本中,您可以使用Form Array.reset()

© www.soinside.com 2019 - 2024. All rights reserved.