Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  32] [ 6]  / answers: 1 / hits: 18801  / 7 Years ago, wed, may 31, 2017, 12:00:00

I have such reactive form:



constructor(...){
this.form = this.formBuilder.group({
name: ['', Validators.compose([Validators.required, Validators.maxLength(50)])],
memes: this.formBuilder.array([
this.initMemes('TrollFace')
])
});
}

initMemes (name?) {
return this.formBuilder.group({
id: [''], name: [name]
});
}


later i can add some more memes:



addMemes () {
const control = <FormArray>this.form.controls['memes'];
control.push(this.initMemes('anyName'));
}


and then if i get form values i get:



this.form.controls['memes'].value - here i have array



But there is a case, when i need this this.form.controls['memes'].value to set to an empty array, how is it possible to do?



If i set it this way:



this.form.controls['memes'].setValue([])



I got error: Must supply a value for form control at index: 0.



what i do wrong?


More From » angular

 Answers
147

EDIT:



As of newer versions, Angular now supports clearing a FormArray with clear():



(<FormArray>this.form.get('memes')).clear();





ORIGINAL:



Tried a few things:reset(),setControl(), but the following was the only solution I found to work that actually resets the whole array to [], other options worked, but they left the formgroups in place, just emptied the values.



So how I got it to work, was to iterate the form array and delete each form group with that particular index in the loop:



const control = <FormArray>this.form.controls['memes'];

for(let i = control.length-1; i >= 0; i--) {
control.removeAt(i)
}


If there is a better way, I'm open for suggestions! :)


[#57615] Saturday, May 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryanulyssesb

Total Points: 91
Total Questions: 105
Total Answers: 102

Location: England
Member since Tue, Sep 8, 2020
4 Years ago
ryanulyssesb questions
Sat, Mar 20, 21, 00:00, 3 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
Mon, Mar 9, 20, 00:00, 4 Years ago
Sun, Jul 7, 19, 00:00, 5 Years ago
;