Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the FormArray values in angular reactive form?

Tags:

angular

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.

like image 859
Mizanur Rahman Avatar asked Aug 25 '26 08:08

Mizanur Rahman


1 Answers

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();
}
like image 116
Nicholas Kurian Avatar answered Aug 27 '26 00:08

Nicholas Kurian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!