In my Angular app i have the following simple form:
<form [formGroup]="loginForm" (submit)="login()">
<div id="container-credentials">
<input type="text" name="username" formControlName="username">
<input type="password" name="password" formControlName="password">
</div>
</form>
When i access the values using the FormGroup
named loginForm
, it works as expected:
login() {
console.log(this.loginForm.value); // {username: "asd", password: "xyz"}
}
But i would like to create a FormData
object from the values using the FormData
constructor.
The FormData
constructor can accept a HTMLFormElement
parameter as explained in its docs:
An HTML element — when specified, the
FormData
object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.
So i've tried adding an id
to my form:
<form id="myForm" [formGroup]="loginForm" (submit)="login()">
And then in login()
:
const myFormElement = document.getElementById('myForm');
const data = new FormData(myFormElement as HTMLFormElement);
console.log(JSON.stringify(data)); // {}
But the FormData
is empty in this case.
I've also tried passing the form directly from the template:
<form [formGroup]="loginForm" (submit)="login($event.target)">
And then:
login(target) {
console.log('Target: ' + target); // Target: [object HTMLFormElement]
const data = new FormData(target);
console.log(JSON.stringify(data)); // {}
}
Still empty.
I've also tried using @ViewChild
with ElementRef
, the result is the same.
I know i could add the values one by one using FormData
methods such as append()
or set()
, but i'd like to create FormData
from more complex structures as well and this would be the easiest way (if it worked).
What am i missing here?
I'd really appreciate any advice.
EDIT:
I've tried to check the FormData
this way as well in all cases:
for (const key of Object.keys(formData)) {
console.log('Key: ' + key);
console.log('Value: ' + formData[key]);
}
I've got no output, which i think also indicates that the FormData
is indeed empty.