angular 2删除formarray中的所有项目

Kar*_*nor 63 angular2-forms angular

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

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

如何清除formarray只有新项目.

我试过这个

const control2 = <FormArray>this.registerForm.controls['other_Partners'];
        control2.setValue([]);
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

有任何想法吗?谢谢

在nginit

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

                }
         
        );

       
        
        

       
    }
Run Code Online (Sandbox Code Playgroud)

点击时不会调用ngonitit

小智 113

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

保留订阅

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

clearFormArray = (formArray: FormArray) => {
  while (formArray.length !== 0) {
    formArray.removeAt(0)
  }
}
Run Code Online (Sandbox Code Playgroud)

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

有关更多信息,请参阅FormArray文档.


更清洁的方法(但打破订阅参考)

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

clearFormArray = (formArray: FormArray) => {
  formArray = this.formBuilder.array([]);
}
Run Code Online (Sandbox Code Playgroud)

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

  • 从Angular 8开始,从FormArray删除所有组件的首选方法是使用`formArray.clear();`。 (23认同)
  • 另外, yourFormArray.setValue([])); 和 yourFormGroup.setControl('yourFormArray', []); (2认同)
  • 用这种方法告别验证 (2认同)

Pia*_*M4n 23

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

this.myForm= {
     name: new FormControl(""),
     desc: new FormControl(""),
     arr: new FormArray([])
}
Run Code Online (Sandbox Code Playgroud)

添点什么 array

const arr = <FormArray>this.myForm.controls.arr;
arr.push(new FormControl("X"));
Run Code Online (Sandbox Code Playgroud)

清除阵列

const arr = <FormArray>this.myForm.controls.arr;
arr.controls = [];
Run Code Online (Sandbox Code Playgroud)

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

arr.removeAt(0)
Run Code Online (Sandbox Code Playgroud)

UPDATE

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

get inFormArray(): FormArray {
    this.myForm.get('inFormArray') as FormArray;
}
Run Code Online (Sandbox Code Playgroud)

并在模板中使用它

<div *ngFor="let c of inFormArray; let i = index;" [formGroup]="i">
other tags...
</div>
Run Code Online (Sandbox Code Playgroud)

重启:

inFormArray.reset();
Run Code Online (Sandbox Code Playgroud)

推:

inFormArray.push(new FormGroup({}));
Run Code Online (Sandbox Code Playgroud)

删除索引处的值:1

inFormArray.removeAt(1);
Run Code Online (Sandbox Code Playgroud)

  • "arr.controls = [];" 提到真的很棒! (4认同)

Par*_*sha 18

简单地

formArray.clear()
Run Code Online (Sandbox Code Playgroud)

就足够了


Maj*_*jiD 16

角 8

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

(this.invoiceForm.controls['other_Partners'] as FormArray).clear();
Run Code Online (Sandbox Code Playgroud)


小智 10

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

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

arr.clear();
console.log(arr.length);  // 0
Run Code Online (Sandbox Code Playgroud)

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

while (arr.length) {
   arr.removeAt(0);
}
Run Code Online (Sandbox Code Playgroud)

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


Ndi*_*EYE 8

(this.questionForm.controls['answers'] as FormArray).clear();
Run Code Online (Sandbox Code Playgroud)


小智 7

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

purgeForm(form: FormArray) {
  while (0 !== form.length) {
    form.removeAt(0);
  }
}
Run Code Online (Sandbox Code Playgroud)


M.R*_*eza 7

您可以轻松地为数组定义一个 getter 并按如下方式清除它:

  formGroup: FormGroup    
  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.formGroup = this.fb.group({
      sliders: this.fb.array([])
    })
  }
  get sliderForms() {
    return this.formGroup.get('sliders') as FormArray
  }

  clearAll() {
    this.formGroup.reset()
    this.sliderForms.clear()
  }
Run Code Online (Sandbox Code Playgroud)


小智 6

从 Angular 8 开始,您可以使用它this.formArray.clear()来清除表单数组中的所有值。这是一个比逐个删除所有元素更简单、更有效的替代方案


zgu*_*gue 5

警告!

Angular v6.1.7 FormArray文档说:

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

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

使用该removeAt功能.

  while (formArray.length !== 0) {
    formArray.removeAt(0)
  }
Run Code Online (Sandbox Code Playgroud)

  • 从Angular 8开始,您可以使用`formArray.clear();` (3认同)

nig*_*2k1 5

更新:Angular 8 终于有了清除数组的方法 FormArray.clear()


Anu*_*iya 5

使用 FormArray.clear() 删除 FormArray 中数组的所有元素