Having an issue with retrieving data from a form submission in Angular. The goal is to receive the user-submitted data wrapped in a single object, utilizing formBuilder. However, it seems that formBuilder only works well with <input>
tags, as mentioned in a relevant Stack Overflow post.
The constructor defines a form and initializes fields using formBuilder:
component.ts
constructor(private formBuilder: FormBuilder) {
this.checkoutForm = this.formBuilder.group({
selectedAccount: '',
selectedContactInfo: '',
});
}
In the HTML file, there are options for users to select from a dropdown menu and checkboxes. While the dropdown selection works fine, applying
formControlName="selectedContactInfo"
to the checkboxes' div
results in an empty string upon form submission.
component.html
<!-- DROPDOWN - WORKS PERFECT -->
<mat-form-field>
<mat-label>CHOOSE ACCOUNT</mat-label>
<mat-select formControlName="selectedAccount">
<mat-option *ngFor="let account of accounts" [value]="account.name">{{account.name}}</mat-option>
</mat-select>
</mat-form-field>
<!-- CHECKBOXES - DOESN'T RETRIEVE DATA WHEN FORM IS SUBMITTED -->
<h2 class="mat-h2">CHOOSE TELEPHONE NUMBERS WE CAN CONTACT YOU ON</h2>
<div formControlName="selectedContactInfo" class="item-container">
<mat-checkbox>{{contactInfo.privateMobile}}</mat-checkbox>
<mat-checkbox>{{contactInfo.workMobile}}</mat-checkbox>
</div>
The objective is to capture and store the checkbox data similarly to how the selected account is handled. Whether one or both checkboxes are chosen, the corresponding mobile numbers should be assigned to selectedContactInfo
. Array declaration for selectedContactInfo: []
was explored but resulted in null values.
Any insights on resolving this matter would be greatly appreciated.
Edit: To verify the correctness of the submitted form data, the following check is made when submitting the form:
onSubmit(userData) {
console.log(userData);
}