angular 2 remove all items from a formarray

后端 未结 15 1662
清歌不尽
清歌不尽 2020-12-07 15:30

I have a form array inside a formbuilder and i am dynamically changing forms, i.e. on click load data from application 1 etc.

The issue i am having is that all the

相关标签:
15条回答
  • 2020-12-07 16:31

    I am very late but I found some other way where you don't need to have loops. you can reset array by setting array control to empty.

    Below code will reset your array.

    this.form.setControl('name', this.fb.array([]))

    0 讨论(0)
  • 2020-12-07 16:33

    Or you can simply clear the controls

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

    Add something array

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

    Clear the array

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

    When you have multiple choices selected and clear, sometimes it doesn't update the view. A workaround is to add

    arr.removeAt(0)
    

    UPDATE

    A more elegant solution to use form arrays is using a getter at the top of your class and then you can access it.

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

    And to use it in a template

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

    Reset:

    inFormArray.reset();
    

    Push:

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

    Remove value at index: 1

    inFormArray.removeAt(1);
    

    UPDATE 2:

    Get partial object, get all errors as JSON and many other features, use the NaoFormsModule

    0 讨论(0)
  • 2020-12-07 16:34

    Angular 8

    simply use clear() method on formArrays :

    (this.invoiceForm.controls['other_Partners'] as FormArray).clear();
    
    0 讨论(0)
提交回复
热议问题