My problem is that I have a form, and when a user submits the form, I want to receive the data which the user has submitted. This data should be wrapped in a single object. I use the formBuilder in Angular, but it seems as if it is mostly possible to retrieve data with formBuilder from <input>
tags (quote from the top answer in this post: "formControlName only works on input, select and textarea. anything that has "value" property."
I have defined a form within my constructor and initialized fields, making use of the formBuilder;
component.ts
constructor(private formBuilder: FormBuilder,
) {
this.checkoutForm = this.formBuilder.group({
selectedAccount: '',
selectedContactInfo: '',
});
}
In my html, I have two places where a user should choose something from; a dropdown-menu and a selection of checkboxes. selectedAccount
from my constructor is applied to <mat-select>
, which works fine; on submission of form, I can see which account I chose. However, it seems that I can't apply formControlName="selectedContactInfo"
to the div
in checkboxes area; it returns empty string.
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>
From the checkboxes, I want to retrieve the actual data. So if the first checkbox has been checked, I want to receive whatever data that contactInfo.privateMobile
contains, probably a string or int of 8 digits, and assign it to selectedContactInfo
in the constructor, in the very same manner I did for selectedAccount
and the dropdown menu.
I want selectedContactInfo
to contain the data for the checkboxes; if both are checked, it returns the mobile numbers for both. If one is checked, it returns that number etc. I also tried with selectedContactInfo: []
in constructor since it needs to return data for all checkboxes, but that just returns null right now.
Thanks in advance.
Edit: For reference (if anyone wants to know this), this is how I check the data when I submit my form to see if it contains right info. Dont know if its relevant:
onSubmit(userData) {
console.log(userData);
}