I have a simple form which includes a toggle switch. It works when I enable the switch, but when I leave it off, the form won't submit. This is my template code
<clr-toggle-container>
<clr-toggle-wrapper>
<input type="checkbox" clrToggle [(ngModel)]="pocTimesheetRequired" name="pocTimesheetRequired"/>
<label>Timesheet Required</label>
</clr-toggle-wrapper>
</clr-toggle-container>
this is my ts file
pocTimesheetRequired: boolean;
onSubmit() {
// tslint:disable-next-line:no-unused-expression
if (this.name) {
this.afs.collection('agencies').add(
{
// agencyId: this.agencyId,
name: this.name,
phone: this.phone,
pocTimesheetRequired: this.pocTimesheetRequired
// logoUrl: this.logoUrl,
// benefitCardPhotoUrl: this.benefitCardPhotoUrl
});
}
}
when I leave the switch off, there is an error as follows:
Function addDoc() called with invalid data. Unsupported field value: undefined (found in field pocTimesheetRequired in document agencies/XwIQmDrnj8ciZST0GmdM).
I feel like I'm missing something that should be obvious, but although I've gone over the docs and searched for an answer everywhere, I cannot figure it out.
The error message provides you with a reason:
Unsupported field value: undefined (found in field pocTimesheetRequired...)
Meaning this.pocTimesheetRequired
is undefined
when sending the data to firestore.
Form control usually does not change the model value unless interacted with. Since this.pocTimesheetRequired
is undefined
during initialization, it's stays undefined until user clicks the checkbox.
To fix the issue I suggest you set a default value for it or replace it on submission:
Solution 1:
pocTimesheetRequired = false;
Solution 2:
phone: this.phone,
pocTimesheetRequired: this.pocTimesheetRequired || false
// logoUrl: this.logoUrl,
You can use ?? false
as well instead of || false
.