在角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);
}

推荐答案

在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();
}

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


Adding another example for people who can't get the above to work

按下按钮:

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

同样的道理也适用于上面,您也可以 Select 将表单传递给newHero函数.

Angular相关问答推荐

导入浏览器模块时出错已导入commonModule的insted,animationBrower也显示错误,当p打开时

Angular 17@在大小写时切换多个值

元件不工作时的Angular 17属性 Select 器

Angular中的Bootstrap carousel动态属性

如何在Angular 17 SSR中处理Swiper 11 Web组件事件

material 对话框中没有合适的注塑

Angular 16+使用ngTemplateOutlet有条件地呈现几个模板中的一个

错误TS2531:对象可能为空.论窗体数组控件

出错后可观察到的重用

当快速拖动光标时会丢失元素 - Angular

如何在 Angular 中每 x 秒从 REST api 加载数据并更新 UI 而不会闪烁?

如何从2个api获取数据并查看Angular material 表中的数据?

需要做什么才能使 ErrorHandler 正常工作?

如果Angular 数据为空,如何设置N/A

清除Angular2中的输入文本字段

angular2:错误: TypeError: Cannot read property '...' of undefined

Angular 应用程序中的语法错误:Unexpected token <

Lint 错误:实现生命周期挂钩接口

ng build 时超出调用重试次数异常

在渲染视图/模板之前等待 Angular 2 加载/解析模型