[angular] Angular의 FormArray에서 모든 항목 제거

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

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

새 항목 만 포함하도록 FormArray를 지우려면 어떻게해야합니까?

나는 이것을 시도했다

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

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

어떤 아이디어?

ngOnInit(): void {
  this.route.params.subscribe(params => {
    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 });
      }
    });
}

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



답변

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

구독 유지

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

업데이트 2 :

부분 개체 가져 오기, 모든 오류를 JSON 및 기타 많은 기능으로 가져 오고 , NaoFormsModule을 사용합니다 .


답변

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


답변

각도 8

clear()formArrays에서 메소드를 사용 하십시오.

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


답변

Angular v4.4는 FormArray의 인스턴스에 동일한 참조를 저장해야하는 경우 다음을 시도하십시오.

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


답변

경고!

Angular v6.1.7 FormArray 문서 는 다음과 같이 말합니다.

배열의 컨트롤을 변경하려면 FormArray 자체에서 push, insert 또는 removeAt 메서드를 사용합니다. 이러한 메서드는 폼의 계층 구조에서 컨트롤이 제대로 추적되도록합니다. FormArray를 직접 인스턴스화하는 데 사용되는 AbstractControls의 배열을 수정하지 마십시오. 변경 감지 중단과 같은 이상하고 예기치 않은 동작이 발생할 수 있습니다.

제안 된 답변 중 하나로 배열에서 splice직접 함수를 사용하는 경우이를 염두에 두십시오 controls.

removeAt기능을 사용하십시오 .

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


답변

배열에 대한 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()
  }