【问题标题】:how to reset angular form and set default values after submitting提交后如何重置角度形式并设置默认值
【发布时间】:2018-04-17 05:05:56
【问题描述】:

我的预期结果是在提交表单后重置表单,并将其默认值设置为绑定到 formGroup 控件。提交后,我尝试通过在表单提交上调用 reset() 将表单重置为其默认数据。请告诉我如何重置日期和时间字段中的默认值。

例子:

pickupDate = new Date().toISOString().slice(0,10);
pickupTime = moment().format() ;

onSubmit(orderData: Order){
        this.apiService(orderData).subscribe( order => {
                 orderForm.reset()
})
}

请帮忙 谢谢

【问题讨论】:

  • 您必须将模型属性设置为空字符串。清除表单不会达到您的预期。
  • 你可以给表单打补丁或者重置后重新构建表单。
  • @RandyCasburn 将表单字段重置为空字符串将无法有效添加我的表单组有很多字段。
  • @AnuradhaGunasekara 您能否更清楚地了解我如何使用 patchValue 实现这一目标。
  • 我的表单组看起来类似于:this.orderForm = fb.group({pickupDate: [this.pickupDate, Validators.required],pickupTime: [this.pickupTime, Validators.required] })

标签: angular angular-forms


【解决方案1】:

提交表单后。你在打电话

this.yourForm.reset()

然后您可以像这样将初始值修补到表单中。

this.yourForm.patchValue({
  firstControllerName: this.initialValues.value1,
  secondControllerName: this.initialValues.value2,
  // other controller names goes here
});

希望这会有所帮助。

【讨论】:

  • 谢谢,我在调用reset后重新初始化表单
【解决方案2】:

您可以像这样同时重置和设置所需的默认值:

    defaultFormValues: any = {
        date: Date.now
    };

    formG: FormGroup = new FormGroup({
        'date': new FormControl(this.defaultFormValues.date)
    });

    onSubmit(orderData: Order) {
        this.apiService(orderData).subscribe(order => {
            this.formG.reset(this.defaultFormValues);
        });
    }

【讨论】:

    【解决方案3】:

    我不知道你的 formBuilder 长什么样,但是

    this.yourForm.reset({}) 已经可以清空未预先确定的字段。你可以尝试类似的事情......

      ngOnChanges() {
        this.queryForm.reset({
        });
    
        // We generate an empty form again. 
        this.createForm();
      }
    

    您的 createForm 可能看起来像这样......

    createForm() {
    
        // As the method name suggests, we create a form. A form consists of Groups, Controls - and optionally - Arrays...
        this.queryForm = new FormGroup({
          query: new FormControl(''),
    
          formArray: new FormArray([this.initQueryConditions())
        })
      }
    

    【讨论】:

      【解决方案4】:

      清除方法取决于您使用的是模板驱动表单还是响应式表单。

      Angular Forms, check full syntax with explaination

      如果是模板,则需要将模型对象设置为默认值(不一定为空)。 如果是响应式的,则调用一个明确清空每个表单值的方法。

      之后,执行 form.Reset 以将其移回“原始 | 未更改”状态,从而也删除验证器

      【讨论】:

        猜你喜欢
        • 2020-03-31
        • 2020-07-12
        • 2019-02-28
        • 1970-01-01
        • 2020-08-07
        • 2020-11-14
        • 2015-02-21
        • 2023-03-17
        • 2018-10-22
        相关资源
        最近更新 更多