UFO ET IT

각도 2 formarray에서 모든 항목을 제거

ufoet 2020. 12. 10. 20:46
반응형

각도 2 formarray에서 모든 항목을 제거


formbuilder 내부에 양식 배열이 있고 양식을 동적으로 변경하고 있습니다. 즉, 응용 프로그램 1에서 데이터를 클릭하여로드합니다.

내가 가지고있는 문제는 모든 데이터가로드되지만 formarray의 데이터는 그대로 유지되고 이전 항목을 새 항목과 연결한다는 것입니다.

새 항목 만 가지도록 형식을 지우려면 어떻게해야합니까?

나는 이것을 시도했다

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

하지만 작동하지 않습니다.

어떤 아이디어? 감사

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

                }
         
        );

       
        
        

       
    }

ngonitit는 클릭시 호출되지 않습니다.


나는 같은 문제가 있었다. 이 문제를 해결하는 방법에는 두 가지가 있습니다.

구독 유지

removeAt(i)루프 에서 함수를 호출하여 각 FormArray 요소를 수동으로 지울 수 있습니다 .

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

이 접근 방식의 장점 formArray은에 등록 된 것과 같은 에 대한 모든 구독 formArray.valueChanges이 손실되지 않는다는 것입니다.

자세한 정보는 FormArray 문서 를 참조하십시오.


더 깨끗한 방법 (그러나 구독 참조가 중단됨)

전체 FormArray를 새 것으로 바꿀 수 있습니다.

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

이 접근 방식은 formArray.valueChangesObservable을 구독하는 경우 문제를 일으 킵니다 ! FromArray를 새 배열로 바꾸면 구독중인 Observable에 대한 참조를 잃게됩니다.


또는 간단히 컨트롤을 지울 수 있습니다.

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)

최신 정보

양식 배열을 사용하는 더 우아한 솔루션은 클래스 맨 위에있는 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);

Angular 8+ clear()부터는 FormArray의 모든 컨트롤을 제거 하는 사용할 수 있습니다 .

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

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

For previous versions the recommended way is:

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

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


Angular v4.4 if you need to save the same reference to the instance of FormArray try this:

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

Warning!

The Angular v6.1.7 FormArray documentation says:

To change the controls in the array, use the push, insert, or removeAt methods in FormArray itself. These methods ensure the controls are properly tracked in the form's hierarchy. Do not modify the array of AbstractControls used to instantiate the FormArray directly, as that result in strange and unexpected behavior such as broken change detection.

Keep this in mind if you are using the splice function directly on the controls array as one of the answer suggested.

Use the removeAt function.

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

Provided the data structure for what you will be replacing the information in the array with matches what is already there you can use 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 Patches the value of the FormArray. It accepts an array that matches the structure of the control, and will do its best to match the values to the correct controls in the group.

It accepts both super-sets and sub-sets of the array without throwing an error.

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

Alternatively you could use reset

reset(value?: any, {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void Resets the FormArray. This means by default:

The array and all descendants are marked pristine The array and all descendants are marked untouched The value of all descendants will be null or null maps You can also reset to a specific form state by passing in an array of states that matches the structure of the control. The state can be a standalone value or a form state object with both a value and a disabled status.

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

OR

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 a forked Plunker demo from some earlier work of mine demoing a very simple utilization of each.


Update: Angular 8 finally got method to clear the Array FormArray.clear()


Angular 8

simply use clear() method on formArrays :

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

While loop will take long time to delete all items if array has 100's of items. You can empty both controls and value properties of FormArray like below.

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


in lastest version, you can use FormArray.reset()


To keep the code clean I have created the following extension method for anyone using Angular 7 and below. This can also be used to extend any other functionality of 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;
}


Since Angular 8 you can use this.formArray.clear() to clear all values in form array. It's a simpler and more efficient alternative to removing all elements one by one


I never tried using formArray, I have always worked with FormGroup, and you can remove all controls using:

Object.keys(this.formGroup.controls).forEach(key => {
          this.formGroup.removeControl(key);
        });

being formGroup an instance of FormGroup.

참고URL : https://stackoverflow.com/questions/41852183/angular-2-remove-all-items-from-a-formarray

반응형