从 Angular 中的 FormArray 中删除所有项目 [英] Remove all items from a FormArray in Angular

查看:40
本文介绍了从 Angular 中的 FormArray 中删除所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我遇到的问题是所有数据都加载了,但 FormArray 中的数据保持不变,只是将旧项目与新项目连接起来.

如何清除 FormArray 以仅包含新项目.

我已经试过了

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

但它不起作用.

有什么想法吗?

ngOnInit(): void {this.route.params.subscribe(params => {如果(参数['id']){this.id = Number.parseInt(params['id']);} else { this.id = null;}});if (this.id != null && this.id != NaN) {警报(this.id);this.editApplication();this.getApplication(this.id);} 别的 {this.newApplication();}}onSelect(已编辑的应用程序:应用程序){this.router.navigate(['/apply', Editedapplication.id]);}编辑应用程序(){this.registerForm = this.formBuilder.group({id:空,type_of_proposal: ['', Validators.required],标题: ['', [Validators.required, Validators.minLength(5)]],Lead_teaching_fellow: ['', [Validators.required, Validators.minLength(5)]],描述:['', [Validators.required, Validators.minLength(5)]],地位: '',用户 ID:JSON.parse(localStorage.getItem('currentUser')).用户名,contactEmail: JSON.parse(localStorage.getItem('currentUser')).email,前名:JSON.parse(localStorage.getItem('currentUser')).firstname,姓氏:JSON.parse(localStorage.getItem('currentUser')).surname,line_manager_discussion: 真,document_url: '',关键字:['', [Validators.required, Validators.minLength(5)]],财务_详细信息:this.formBuilder.group({id:空,buy_expertise_description: ['', [Validators.required, Validators.minLength(2)]],buy_expertise_cost: ['', [Validators.required]],buy_out_teaching_fellow_cost: ['', [Validators.required]],buy_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]],}),合作伙伴:this.formBuilder.array([//this.initEditPartner(),//this.initEditPartner()//this.initMultiplePartners(1)]),other_Partners: this.formBuilder.array([//this.initEditOther_Partners(),])});}获取应用程序(ID){this.applicationService.getAppById(id, JSON.parse(localStorage.getItem('currentUser')).username).subscribe(响应 => {if (Response.json() == false) {this.router.navigateByUrl('/');} 别的 {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 替换整个 FormArray.

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

<块引用>

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

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 data loads in but the data in the FormArray stays and just concats the old items with new.

How do I clear that FormArray to only have the new items.

I've tried this

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

but it doesn't work.

Any ideas?

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 is not being called on click

解决方案

I had same problem. There are two ways to solve this issue.

Preserve subscription

You can manually clear each FormArray element by calling the removeAt(i) function in a loop.

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

The advantage to this approach is that any subscriptions on your formArray, such as that registered with formArray.valueChanges, will not be lost.

See the FormArray documentation for more information.


Cleaner method (but breaks subscription references)

You can replace whole FormArray with a new one.

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

This approach causes an issue if you're subscribed to the formArray.valueChanges observable! If you replace the FromArray with a new array, you will lose the reference to the observable that you're subscribed to.

这篇关于从 Angular 中的 FormArray 中删除所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆