重置表单的最干净方法 [英] Cleanest way to reset forms

查看:78
本文介绍了重置表单的最干净方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the cleanest way to reset forms in Angular 2 latest version? I would like to reset the input textboxes after adding a post.

@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);
}

推荐答案

添加对 ngForm的引用指令在您的html代码中,这使您可以访问表单.

Add a reference to the ngForm directive in your html code and this gives you access to the form.

<form #myForm="ngForm" (ngSubmit)="addPost(); myForm.reset()"> ... </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();
}

resetForm 之间的区别和 reset 是,前者将清除表单字段以及任何验证,而后面的内容只会清除这些字段.验证并提交表单后,请使用 resetForm .否则,请使用 reset .

The difference between resetForm and reset is that the former will clear the form fields as well as any validation, while the later will only clear the fields. Use resetForm after the form is validated and submitted, otherwise use reset.

为无法满足以上条件的人们添加另一个示例.

按下按钮:

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

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

Same thing applies above, you can also choose to pass the form to the newHero function.

这篇关于重置表单的最干净方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆