加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 最简洁的方式来重置表单

发布时间:2020-12-17 07:54:37 所属栏目:安全 来源:网络整理
导读:在Angular 2最新版本中重置表单的最简洁方法是什么?我想在添加帖子后重置输入文本框. @Component({ selector: 'post-div',template: ` h2Posts/h2 form (submit)="addPost()" labelTitle: /labelinput type="text" name="title" [(ngModel)]="title"br/ lab
在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);
}
<form #myForm="ngForm" (submit)="addPost(); myForm.reset()"> ... </form>

要么:

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

为无法完成上述工作的人添加另一个示例.

按下按钮:

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

同样适用于上述内容,您也可以选择将表单传递给newHero函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读