Angular响应式表单:ngOnInit设置值后无法获取输入框值
问题原因
Angular表单中,被禁用的控件不会被包含在form.value的返回结果里。你给createdBy控件赋值后立刻调用了disable(),导致提交时this.commentForm.value中没有该字段,最终comment.createdBy为undefined。
解决方案
将提交时使用的this.commentForm.value替换为this.commentForm.getRawValue(),这个方法会返回表单所有控件的值,包括已禁用的控件:
修改onSubmit()函数:
onSubmit() { this.webService.postClubComment(this.commentForm.getRawValue()).subscribe((response: any) => { this.commentForm.reset(); window.location.reload(); }); }
额外优化方案
如果createdBy是无需用户编辑的固定值,完全可以不用将其加入表单控件,直接在请求方法中从sessionStorage取值,简化逻辑:
postClubComment(comment: any) { let postData = new FormData(); postData.append("createdBy", sessionStorage['name']); postData.append("comment", comment.comment); let today = new Date(); let todayDate = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate(); postData.append("date", todayDate) return this.http.post(this.URL + this.clubId + "/comments", postData); }
这样就省去了表单控件的赋值和禁用操作,代码更简洁。
内容的提问来源于stack exchange,提问作者user13217309
相关产品推荐
相关产品推荐

