我在formbuilder中有一个表单数组,我正在动态更改表单,即从应用程序1等点击加载数据。
我遇到的问题是加载了所有数据,但是formarray中的数据仍然保留,只是用旧的项目连接旧项目。
如何清除formarray只包含新项目。
我试过这个
const control2 = <FormArray>this.registerForm.controls['other_Partners'];
control2.setValue([]);
但它没有用。
有什么想法吗? 感谢
in 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 });
}
}
);
}
&#13;
点击
时未调用ngonitit答案 0 :(得分:82)
我有同样的问题。有两种方法可以解决这个问题。
您可以通过在循环中调用removeAt(i)
函数来手动清除每个FormArray元素。
clearFormArray = (formArray: FormArray) => {
while (formArray.length !== 0) {
formArray.removeAt(0)
}
}
此方法的优势在于,
formArray
上的所有订阅(例如使用formArray.valueChanges
注册的订阅)都不会丢失。
有关详细信息,请参阅FormArray documentation。
您可以用新的FormArray替换整个FormArray。
clearFormArray = (formArray: FormArray) => {
formArray = this.formBuilder.array([]);
}
如果您订阅了
formArray.valueChanges
可观察对象,则此方法会导致问题!如果用新数组替换FromArray,您将失去对您订阅的observable的引用。
答案 1 :(得分:22)
或者您可以简单地清除控件
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 :(得分:7)
Angular v4.4如果你需要保存对FormArray实例的相同引用,试试这个:
purgeForm(form: FormArray) {
while (0 !== form.length) {
form.removeAt(0);
}
}
答案 3 :(得分:6)
您可以轻松地为数组定义一个吸气剂,并按如下所示清除它:
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()
}
答案 4 :(得分:4)
使用FormArray.clear()删除FormArray中数组的所有元素
答案 5 :(得分:3)
如果您要替换数组中的信息的数据结构与已经存在的匹配,您可以使用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修补FormArray的值。它 接受一个与控件结构匹配的数组,并且会 尽力将值与组中正确的控件匹配。
它接受数组的超集和子集而不抛出 错误。
const arr = new FormArray([
new FormControl(),
new FormControl()
]);
console.log(arr.value); // [null, null]
arr.patchValue(['Nancy']);
console.log(arr.value); // ['Nancy', null]
或者您可以使用reset
reset(value?:any,{onlySelf,emitEvent}?:{onlySelf?:boolean, emitEvent?:boolean}):void重置FormArray。这意味着 默认值:
数组和所有后代都标记为pristine数组和所有 后代被标记为未触及所有后代的值将是 null或null映射您还可以通过重置为特定的表单状态 传递与数组结构相匹配的状态数组 控制。状态可以是独立值或表单状态对象 同时具有值和禁用状态。
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来自我早期工作的一个分叉的Plunker演示,演示了每个的非常简单的利用。
答案 6 :(得分:2)
从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);
}
答案 7 :(得分:1)
更新:Angular 8终于有了清除数组的方法 FormArray.clear()
答案 8 :(得分:1)
角度8
仅在formArrays上使用clear()
方法:
(this.invoiceForm.controls['other_Partners']).clear();
答案 9 :(得分:1)
我从未尝试过使用formArray,我一直使用FormGroup,并且可以使用以下方法删除所有控件:
Object.keys(this.formGroup.controls).forEach(key => {
this.formGroup.removeControl(key);
});
成为formGroup的FormGroup实例。
答案 10 :(得分:1)
我来晚了,但是我发现了其他不需要循环的方式。您可以通过将数组控件设置为空来重置数组。
下面的代码将重置您的阵列。
this.form.setControl('name', this.fb.array([]))
答案 11 :(得分:0)
为了保持代码整洁,我为使用Angular 7及更低版本的任何人创建了以下扩展方法。这也可以用于扩展反应式表单的任何其他功能。
<button class="mdc-icon-button material-icons mdc-top-app-bar__navigation-icon">menu</button>
答案 12 :(得分:0)
如果您使用的是 Angular 7 或以前的版本并且您无法访问 clear() 方法,则有一种方法可以在不执行任何循环的情况下实现:
yourFormGroup.controls.youFormArrayName = new FormArray([]);
答案 13 :(得分:0)
自Angular 8起,您可以使用this.formArray.clear()
清除表单数组中的所有值。
这是一种更简便,更有效的替代方法,可以一次删除所有元素
答案 14 :(得分:0)
在最新版本中,您可以使用FormArray.reset()
答案 15 :(得分:0)
如果数组具有100个项目,则循环将花费很长时间删除所有项目。您可以像下面那样清空FormArray的控件和值属性。
clearFormArray =(formArray:FormArray)=> {formArray.controls = []; formArray.setValue([]); }
答案 16 :(得分:-1)
简单
formArray.clear()
就够了