【问题标题】:Cleanest way to reset forms重置表单的最简洁方法
【发布时间】:2021-12-23 18:43:33
【问题描述】:

在 Angular 2 最新版本中重置表单最简洁的方法是什么?添加帖子后,我想重置输入文本框。

@Component({
  selector: 'post-div',
  template: `
            <h2>Posts</h2>
            <form (submit)="addPost()">
                <label>Title: </label><input type="text" name="title" [(ngModel)]="title"><br/>
                <label>Body: </label><input type="text" name="body" [(ngModel)]="body"><br/>
                <input type="submit" value="Add Post">
            </form>
            <ul>
                <li *ngFor="let post of posts">
                    <strong>{{post.title}}</strong>
                    <p>{{post.body}}</p>
                </li>
            </ul>
          `,
  providers: [PostService]
});

addPost(){
    this.newPost = {
        title: this.title,
        body: this.body
    }
    this._postService.addPost(this.newPost);
}

【问题讨论】:

    标签: angular forms


    【解决方案1】:

    在您的 html 代码中添加对 ngForm 指令的引用,这样您就可以访问表单,因此您可以使用 .resetForm()

    <form #myForm="ngForm" (ngSubmit)="addPost(); myForm.resetForm()"> ... </form>
    

    ...或者将表单传递给函数:

    <form #myForm="ngForm" (ngSubmit)="addPost(myForm)"> ... </form>
    
    addPost(form: NgForm){
        this.newPost = {
            title: this.title,
            body: this.body
        }
        this._postService.addPost(this.newPost);
        form.resetForm(); // or form.reset();
    }
    

    resetFormreset 的区别在于前者会清除表单字段以及任何验证,而后者只会清除字段。表单验证提交后使用resetForm,否则使用reset


    为无法使用上述方法的人添加另一个示例

    按下按钮:

    <form #heroForm="ngForm">
        ...
        <button type="button" class="btn btn-default" (click)="newHero(); heroForm.resetForm()">New Hero</button>
    </form>
    

    上面同样适用,您也可以选择将表单传递给newHero 函数。

    【讨论】:

    • 这不再起作用了。即使在角度示例中 -> angular.io/guide/form-validation 如果您第二次按下“重置的新英雄”,它仍然会显示“需要名称”验证错误???步骤是:按“新英雄”,输入新值并再次按“新英雄”。表单被重置时不应出现验证错误???
    • 你在我解释的步骤中尝试过他们的例子吗?我的意思是如果表单被重置并且是原始的,那么你不应该得到验证错误。
    • 重置将清除整个表单并将其状态移回原始状态(不触发验证),而 resetForm 只会清除值而不更改状态,本质上是 'textbox.clear' 操作前几天
    • 也许@user1829319 的意思是,即使在调用'form.reset()' - github.com/angular/components/issues/4190
    • reset the whole form 及其验证,您必须转到resetForm() 方法。如果您只想重置值,请使用reset() 方法。
    【解决方案2】:

    清除表单及其错误状态(脏、原始等)的最简单、最干净的方法

    this.formName.reset();
    

    有关此处阅读的表格的更多信息

    PS:当您提出问题时,您的问题代码中没有使用表单,您使用的是使用 ngModel 的简单两天数据绑定,而不是 formControl

    form.reset() 方法仅适用于 formControls 重置调用

    【讨论】:

      【解决方案3】:

      清除表格的最简单方法

      <form #myForm="ngForm" (submit)="addPost();"> ... </form>
      

      然后在 .ts 文件中,您需要访问模板的局部变量,即

      @ViewChild('myForm') mytemplateForm : ngForm; //import { NgForm } from '@angular/forms';
      

      要重置值和状态(原始,触摸..),请执行以下操作

      addPost(){
      this.newPost = {
          title: this.mytemplateForm.value.title,
          body: this.mytemplateForm.value.body
      }
      this._postService.addPost(this.newPost);
      this.mytemplateForm.reset(); }
      

      这是清除表单最干净的方法

      【讨论】:

        【解决方案4】:

        通过转换 HTML 元素来使用简单的 HTML 和 javascript 执行此操作,以避免打字稿错误

        &lt;form id="Login"&gt;

        在component.ts文件中,

        clearForm(){
         (<HTMLFormElement>document.getElementById("Login")).reset();
        }
        

        方法clearForm() 可以根据需要在任何地方调用。

        【讨论】:

          【解决方案5】:

          在 Angular 13 中添加了一个有趣的功能:创建表单控件时,您可以使用 initialValueIsDefault 选项,因此在使用 reset() 时,表单的值将设置为其初始值。

          如果您有重置按钮或类似的逻辑,我发现这对较大的表单非常有用。

          更多信息请参考 GitHub 上的功能 PR:https://github.com/angular/angular/pull/44434

          【讨论】:

            【解决方案6】:

            组件.html (你命名你的形式)

            <form [formGroup]="contactForm">
            

            (添加点击事件(click)="clearForm())

            <button (click)="onSubmit()" (click)="clearForm()" type="submit" class="btn waves-light" mdbWavesEffect>Send<i class="fa fa-paper-plane-o ml-1"></i></button>
            

            组件.ts

             clearForm() {
                         this.contactForm.reset();
                        }
            

            查看所有代码:https://ewebdesigns.com.au/angular-6-contact-form/ 如何使用 firebase 添加联系表单

            【讨论】:

              【解决方案7】:

              Angular 反应式表单:

              onCancel(): void {
                this.registrationForm.reset();
                this.registrationForm.controls['name'].setErrors(null);
                this.registrationForm.controls['email'].setErrors(null);
              }
              

              【讨论】:

                【解决方案8】:

                仅使用reset() 方法重置表单。它会重置表单,但您可能会遇到问题,例如 验证错误 - 例如:Name is required

                要解决这个问题,请使用resetForm() 方法。它会重置表单并重置提交状态以解决您的问题。

                resetForm() 方法实际上是在调用 reset() 方法,另外它正在重置提交状态。

                【讨论】:

                  【解决方案9】:
                  this.<your_form>.form.markAsPristine();
                  this.<your_form>.form.markAsUntouched();
                  this.<your_form>.form.updateValueAndValidity();
                  

                  也可以帮忙

                  【讨论】:

                    【解决方案10】:

                    在angular2+中用按钮清除表单的最简单方法是

                    使用 # 为您的表单命名

                    <form #your_form_name (ngSubmit)="submitData()"> </form>
                    
                    <button (click)="clearForm(Your_form_name)"> clear form </button>
                    

                    在您的 component.ts 文件中

                    clearForm(form: FormGroup) {
                    form.reset();
                    }
                    

                    【讨论】:

                      【解决方案11】:

                      这里有很多答案,但没有答案将参数传递给 NgForm 中的 reset 函数。


                      您必须传递带有一些值的输入字段的名称,这些值将被初始化为您在重置表单后通过 angular 传递的相同默认值。 这是 HTML 文件中的表单

                      <form (ngSubmit)="onSubmit()" #f="ngForm">
                          <label for="username">Username</label>
                          <input type="text" ngModel name="username" required>
                      
                          <label for="email">Mail</label>
                          <input type="email" ngModel name="email" required email>
                      
                          <label for="secret">Secret Questions</label>
                          <select name="secret" ngModel>
                              <option value="" disabled hidden selected>Select your option</option>
                              <option value="pet">Your first Pet?</option>
                              <option value="teacher">Your first teacher?</option>
                          </select>
                      
                          <button type="button" (click)="reset()">Reset</button>
                          <button type="submit">Submit</button>
                      </form>
                      

                      这是您的 .component.ts 文件

                      export class AppComponent {
                      
                          @ViewChild('f') signupForm: NgForm    // import { NgForm } from '@angular/forms';
                      
                          reset() {
                              this.signupForm.reset({
                                  "username": "",
                                  "email": "",
                                  "secret": ""
                              })
                          }
                      
                          onSubmit() {
                              console.log(this.signupForm.value)
                          }
                      }
                      

                      如果你没有为“secret”提供默认值,那么这真的很有帮助,那么按下重置按钮后的输入框将变为空(“”)。将不会为其设置默认值。但现在重置后,其默认值将设置为“”,因此在选择字段默认值内,即“选择您的选项”文本将被看到。 请注意,如果您不想为其提供任何默认值,也可以省略任何字段。

                      【讨论】:

                        【解决方案12】:

                        要重置表单,请使用与来自组的相同结构中的表单名称调用重置函数

                        addPost(){
                            this.newPost = {
                                title: this.title,
                                body: this.body
                            }
                            this.formName.reset({
                                "title": '',
                                "body": ''
                            });
                        }
                        

                        【讨论】:

                          【解决方案13】:

                          你也可以通过 JavaScript 来实现:

                          (document.querySelector("form_selector") as HTMLFormElement).reset();
                          

                          【讨论】:

                          • 对不起,它不起作用,“'元素'类型上不存在属性'reset'。
                          • 哦,对不起,确实。在 JavaScript 中它可以工作,但 typescript 不知道类型。我已经更新了代码。所以,现在编译器不应该显示这样的错误。谢谢,你提到了!
                          【解决方案14】:
                              //Declare the jquery param on top after import
                          declare var $: any;
                          declare var jQuery: any;
                          
                          clearForm() {
                              $('#contactForm')[0].reset();
                          }
                          

                          【讨论】:

                          • 将 jquery 添加到 Angular 应用程序中是不受欢迎的。
                          猜你喜欢
                          • 2012-02-11
                          • 1970-01-01
                          • 2010-10-24
                          • 2010-12-06
                          • 1970-01-01
                          相关资源
                          最近更新 更多