Here, I want to make the FormArray's length zero. (it is mentioned that everything works fine with this form)
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>
here, I want to empty the nod_tags value and console.log() should return an empty array.
In the resetTags()
, get the corresponding value of the FormControl that you require. Now you can call the reset() on it as shown below:
resetTags() {
this.profileForm.controls['nod_tags'].reset();
}
From your comment, to set it to an empty array use:
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);
}
This way worked very well. Thanks everyone.
I think this is the way you want to do it
resetTags() {
this.nodTags.clear();
}
get nodTags(): FormArray {
return this.profileForm.get('nod_tags') as FormArray;
}
I also made a small demo
The best way to do this as of Angular 8+ is with the clear() method provided with FormArray
:
// Reset all tags (Angular 8+)
resetTags() {
const nodTags = this.profileForm.get('nod_tags') as FormArray;
if ( nodTags.length > 0 )
nodTags.clear();
}
If you're using Angular 7 or below, then Mizanur's version will work. Here's a modified version of the resetTags()
method that uses it:
// Reset all tags (Angular 7 and below)
resetTags() {
const nodTags = this.profileForm.get('nod_tags') as FormArray;
while ( nodTags.length > 0 ) {
nodTags.removeAt(0);
}
try this,
this.form = this._formB.group({ blocks: this._formB.array(["a","b","c"]) }); this.form.controls['blocks'].value.length = 0;
there is more simple way to make nod_tags Empty!
get nod_tagsArray() {
return this.profileForm.controls.nod_tags as FormArray;
}
this.nod_tagsArray.controls =[];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.