在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>