var formData = new FormData(); Object.keys(this.myForm.value).forEach((key) => {…
- User
var formData = new FormData(); Object.keys(this.myForm.value).forEach((key) => { console.log(this.myForm.get[key.toString()]); formData.append(key, this.myForm.get[key]); });
// Append the file if it exists if (this.itemImageFile) { formData.append("image", this.itemImageFile); } console.log(formData);what issue here?
- Assistant
Your code is attempting to create a
FormDataobject and populate it with the values from a form. However, it contains a couple of issues that may lead to incorrect behavior:-
Accessing form control values: When using
this.myForm.get, you should use parentheses to call the method, like this:this.myForm.get(key)instead of usingthis.myForm.get[key]. The correct access should look like this:console.log(this.myForm.get(key)); -
Getting the value from the form control: After you get the control using
.get(key), you need to retrieve the value by accessing.valueon the control. For instance, the code should be:formData.append(key, this.myForm.get(key).value);
Here’s the corrected version of your code:
-