我有一个表单,允许用户在我的Angular 5应用程序中发表评论。
我正在尝试在发布评论后清除表单,但收到验证错误,就好像表单已提交两次一样。
~/.bashrc
和html:
export class CommentCreateComponent implements OnInit {
@Output() newComment = new EventEmitter<Comment>();
comment: Comment = {
content: '',
author: '',
};
constructor(
private commentService: CommentService) { }
onSubmit() {
var self = this;
this.commentService.createComment(this.comment)
.subscribe(
result => {
this.newComment.emit(result as Comment);
// The next line causes me problems.
// this.requestComment.content = '';
},
error => {
});
}
}
一切都适用于上述情况,但问题是,一旦用户发布评论,文本框中仍然会包含旧文本。
如果我取消注释这一行:
<form name="form"
(ngSubmit)="createComment.form.valid && onSubmit()"
#createRequestComment="ngForm"
novalidate>
<textarea name="content"
minlength="2"
required
maxlength="300"
id="content"
#content="ngModel"
[(ngModel)]="comment.content" ></textarea>
<div *ngIf="content.invalid && createRequestComment.submitted"
class="text-danger">
Comment is required and must be between 2 and 300 characters long.
</div>
<button type="submit" class="button">Post Comment</button>
</form>
然后评论被发布,文本框被清除,但我的验证错误显示出来。
我做错了什么?
答案 0 :(得分:0)
将表单的引用传递给onSubmit
。
<form name="form"
(ngSubmit)="createComment.form.valid && onSubmit(createRequestComment)"
^^^^^^^^^^^^^^^^^^^^
#createRequestComment="ngForm"
novalidate>
在onSubmit
中,请致电form.resetForm()
以完全重置您的表单,而不是this.requestComment.content = ''
。
onSubmit(form: NgForm) {
...
form.resetForm();
...
}