angular 2删除formarray中的所有项目
我在formbuilder中有一个表单数组,我正在动态更改表单,即从应用程序1等点击加载数据.
我遇到的问题是所有数据都加载但是formarray中的数据保持不变,只是将旧项目与新项目连接起来. 如何清除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: ['',description: ['',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: ['',financial_Details: this.formBuilder.group({ id: null,buying_expertise_description: ['',Validators.minLength(2)]],buying_expertise_cost: ['',[Validators.required]],buying_out_teaching_fellow_cost: ['',buying_out_teaching_fellow_desc: ['',travel_desc: ['',travel_cost: ['',conference_details_desc: ['',conference_details_cost: ['',}),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 documentation. 更清洁的方法(但打破订阅参考) 您可以使用新的FormArray替换整个FormArray. clearFormArray = (formArray: FormArray) => { formArray = this.formBuilder.array([]); }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |