简体   繁体   English

使用 Firebase 数据库关闭切换时,带有切换复选框的表单不提交

[英]form with toggle checkbox doesn't submit when toggle is off using Firebase database

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这是我的 ts 文件

  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...)不支持的字段值:未定义(在字段 pocTimesheetRequired... 中找到)

Meaning this.pocTimesheetRequired is undefined when sending the data to firestore.这意味着将数据发送到 Firestore 时undefined this.pocTimesheetRequired

Form control usually does not change the model value unless interacted with.除非与之交互,否则表单控件通常不会更改 model 值。 Since this.pocTimesheetRequired is undefined during initialization, it's stays undefined until user clicks the checkbox.由于this.pocTimesheetRequired在初始化期间undefined ,因此在用户单击复选框之前它一直未定义。

To fix the issue I suggest you set a default value for it or replace it on submission:要解决此问题,我建议您为其设置默认值或在提交时替换它:

Solution 1:解决方案1:

pocTimesheetRequired = false;

Solution 2:解决方案2:

phone: this.phone,
pocTimesheetRequired: this.pocTimesheetRequired || false 
// logoUrl: this.logoUrl,

You can use ?? false可以用?? false ?? false as well instead of || false ?? false以及|| false || false . || false的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM