前端之家收集整理的这篇文章主要介绍了
angular – 最简洁的方式来重置表单,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
301_0@
在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函数.