![](/img/trans.png)
[英]Angular Reactive Form : How to preset values ? (FormArray containing objects)
[英]How to clear the FormArray values in angular reactive form?
在这里,我想让 FormArray 的长度为零。 (有人提到这个表格一切正常)
profileForm: FormGroup;
ngOnInit() {
this.profileForm = new FormGroup({
nod_title: new FormControl(),
nod_subtitle: new FormControl(null),
nod_name: new FormControl(null),
nod_occupation: new FormControl(null),
nod_description: new FormControl(null),
nod_tags: new FormArray([new FormControl('hello'), new FormControl('world')]),
});
}
resetTags() {
if (this.profileForm.value.nod_tags.length) { // here I tried
this.profileForm.value.nod_tags.clear();
console.log(this.profileForm.value.nod_tags)
}
<button type="button" (click)="resetTags()"> Reset taggs </button>
在这里,我想清空 nod_tags 值并且 console.log() 应该返回一个空数组。
在resetTags()
,获取您需要的FormControl的相应值。 现在你可以调用reset() ,如下所示:
resetTags() {
this.profileForm.controls['nod_tags'].reset();
}
根据您的评论,要将其设置为空数组,请使用:
resetTags() {
let arr = <FormArray>this.profileForm.controls['nod_tags'];
arr.clear();
}
resetTags() {
const arr = this.profileForm.controls.nod_tags as FormArray;
while (0 !== arr.length) {
arr.removeAt(0);
}
这种方式非常有效。 谢谢大家。
我认为这是你想做的方式
resetTags() {
this.nodTags.clear();
}
get nodTags(): FormArray {
return this.profileForm.get('nod_tags') as FormArray;
}
我也做了一个小demo
从 Angular 8+ 开始,最好的方法是使用FormArray
提供的clear()方法:
// Reset all tags (Angular 8+)
resetTags() {
const nodTags = this.profileForm.get('nod_tags') as FormArray;
if ( nodTags.length > 0 )
nodTags.clear();
}
如果您使用的是 Angular 7 或更低版本,那么 Mizanur 的版本将起作用。 这是使用它的resetTags()
方法的修改版本:
// Reset all tags (Angular 7 and below)
resetTags() {
const nodTags = this.profileForm.get('nod_tags') as FormArray;
while ( nodTags.length > 0 ) {
nodTags.removeAt(0);
}
尝试这个,
this.form = this._formB.group({ blocks: this._formB.array(["a","b","c"]) }); this.form.controls['blocks'].value.length = 0;
有更简单的方法可以使 nod_tags 为空!
get nod_tagsArray() {
return this.profileForm.controls.nod_tags as FormArray;
}
this.nod_tagsArray.controls =[];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.