0

I have a list of replies under a post using *ngFor. This is set up using an array of formGroups. The replies can be updated, created, or deleted by the user. When I edit a reply, I get a response back from the API and use the following code to update the array.

//This is a simplified response from the API
updatedReply = {
  "id": "dajlajg",
  "content": "test"
}

//Find the existing entry and remove it from the existing reply list
this.replyBuilder = this.replyFeedbackForm.value.replies.filter(reply => reply.id !== replyId)

//Add the updated reply back into the list of existing replies
this.replyBuilder = this.replyBuilder.concat(updatedReply)

//Update the value and the view
this.repliesControl.patchValue(this.replyBuilder)

After running code similar to the above, the updated reply contents will display in the view immediately. No problem.

With adding and deleting replies, I follow a similar process for each, but the patchValue does not end up with a similar result. When a reply is added, patchValue does not cause the view to update at all. When a reply is deleted, patchValue overwrites the deleted reply with the reply last in the list of replies.

//Add Reply
newPost = {
  "id": "dahljal",
  "content": "test reply"
}
//When I test this line, I can see it does add the new reply with all the old replies
this.replyBuilder = this.replyFeedbackForm.value.replies.concat(newPost)

this.repliesControl.patchValue(this.replyBuilder)


//Delete Reply
 this.replyBuilder = this.replyFeedbackForm.value.replies.filter(reply => reply.id !== replyId)
this.repliesControl.patchValue(this.replyBuilder)

Could anyone help me understand what I should be doing to update the view after adding and deleting replies when using an array of formGroups?

  • You'll probably want to look into FormArrays: https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays – Brandon Taylor Feb 20 '19 at 17:57
  • This should help you getting started: https://stackoverflow.com/a/43521492/6294072 I think you actually are trying to use a FormArray, correct? It just looks a bit wrong... – AT82 Feb 20 '19 at 18:17
  • I have a complete working example here that adds/removes FormGroups from a FormArray: https://github.com/DeborahK/Angular-ReactiveForms/tree/master/APM – DeborahK Feb 20 '19 at 18:43
  • You can refer this http://keepnote.cc/code/form-group-with-formarray-adding-dyamic-row-angular-5-6 – Paresh Gami Feb 21 '19 at 12:59

0 Answers0