AngularのFormArrayからすべてのアイテムを削除する 質問する

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が呼び出されない

ベストアンサー1

私も同じ問題を抱えていました。この問題を解決するには 2 つの方法があります。

サブスクリプションの維持

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([]);
}

このアプローチでは、Observable をサブスクライブしている場合に問題が発生しますformArray.valueChanges。FromArray を新しい配列に置き換えると、サブスクライブしている Observable への参照が失われます。

おすすめ記事