【问题标题】:How to reset only specific fields of form in angular 5如何仅重置角度5中的特定表单字段
【发布时间】:2018-10-16 06:21:18
【问题描述】:

我在我的一个组件文件中创建了一个函数来重置表单(myform):

`onSubmit() {
  if (this.myform.valid) {
    console.log("Form Submitted!");
    this.myform.reset();
  }
}`

重置整个表单效果很好,但是否可以只重置一些元素并保持其他元素相同。

【问题讨论】:

    标签: angular forms angular5 angular-components


    【解决方案1】:

    试试这个:

    this.myform.controls['comments'].reset()
    

    【讨论】:

    • 如何添加多个字段?说this.myform.controls['comments', 'name'].reset()我在文档中找不到这种方法。
    • @Keithers 试试这个:this.myform.reset({ cmets: null, name: null})
    • @Abdessamad 试过但没用,我不得不为不同的控件名称复制两次代码this.myform.controls['comments'].reset(), this.myform.controls['name'].reset()
    • 我花了很长时间才找到这个,谢谢,我认为这是最干净的解决方案。
    【解决方案2】:

    试试这个:

      clearForm() {
        this.myForm.get('comments').reset();
        this.myForm.get('name').reset();
      }
    

    并在您提交表单的地方调用此函数。

    【讨论】:

      【解决方案3】:

      是的,您可以使用 this.myform.controls 访问控件 获取控件并调用reset()

      【讨论】:

      • 我的一个控件名称是comments,所以我写了this.myform.controls.comments.reset()。但我收到错误“未解析的变量 cmets”
      【解决方案4】:

      更新:

      我刚遇到这个问题,虽然接受的答案有效,但它有一些 tslint 警告。我最终做了:

      this.myForm.get('formControlName').setValue(null);
      

      我正在使用 Angular 8。

      如果您想为多个领域执行此操作,也可以:

      private controlNames = ['nameOne', 'nameTwo'];
      
      this.controlNames.map((value: string) => this.myForm.get(value).setValue(null));
      

      【讨论】:

        【解决方案5】:

        在你的 html 中

        <select formControlName="idSala" (change)="clearField(1)">
         <option value="">Selecione uma sala</option>
        </select>
        

        &lt;input type="text" formControlName="titulo"&gt;

        &lt;input formControlName="dataHoraInicial" type="datetime-local"&gt;

        TS

        clearField(value) {
        if (value == 1) {
          this.formularioDeAgendamentoSala.controls['titulo'].reset();
          this.formularioDeAgendamentoSala.controls['dataHoraInicial'].reset();
        }
        

        }

        【讨论】:

          【解决方案6】:

          动态删除FormControl值:

          private _clearFormGroupControlValue(formControlName: string) {
            this.formGroup.get(formControlName).setValue(null);
          }
          
                                    or
          
          private _clearFormGroupControlValue(formControlName: string) {
            this.formGroup.controls[formControlName].reset();
          }
          
                                    or
          private _clearFormGroupControlValue(formControlName: string) {
            this.formGroup.controls[formControlName].patchValue(null || '');
          }
          
          

          【讨论】:

            猜你喜欢
            • 2023-03-14
            • 2019-03-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-03-29
            • 1970-01-01
            • 2019-05-30
            相关资源
            最近更新 更多