如何验证angular 2表单

如何验证angular 2表单,angular,angular2-forms,Angular,Angular2 Forms,Angular form验证不工作。Angular 2中的验证错误消息未正常工作。我做了部分验证,但未工作。您能找到我的错误所在吗 脚本: submitform(){ alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.myform.value)); alert(this.myform.value.gender); if(this.myform.value.placename) { this.placename=false; } else{

Angular form验证不工作。Angular 2中的验证错误消息未正常工作。我做了部分验证,但未工作。您能找到我的错误所在吗

脚本:

submitform(){

alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.myform.value));

alert(this.myform.value.gender);

if(this.myform.value.placename)
{ 
 this.placename=false;
}
else{
 this.placename=true; 
}
if(this.myform.value.gender)
{
 this.genders=false;
}
else{
 this.genders=true;
}

if(this.myform.value.minAmount)
{
 this.minAmount=false;
}
else{
 this.minAmount=true;
}
if(this.myform.value.maxAmount)
{
 this.maxAmount=false;
} 
else{
 this.maxAmount=true;
}


  if(!this.myform.valid)
  {
  alert("Form Not valid");
  }
  else
  {
  alert("Form valid");   
  }

  }   

因此,您的错误是您手动检查表单值并尝试自己验证它们,而不是依赖给定的表单值

我清理了您的代码,并尝试删除任何不必要的内容。我对我改变的事情留下了评论

以下是我更改的结果:

以下是我所更改内容的详细版本:

  • 在使用表单检查无效值时,不需要使用[{ngModel}]。您可以通过执行类似于
    this.myform.controls['placename'].value的操作来访问表单值。所以我删除了你所有的ngModels和你所有的if语句,检查它们是否有效
  • 我添加了一个布尔值
    formSubmitted
    ,当用户尝试提交表单时,该值设置为true
  • 为了在打开页面时不会立即出现红色文本,我让验证(错误文本)仅在用户尝试提交无效数据后显示。为此,我检查表单值是否有效,以及用户是否已经尝试提交表单。例如,在html中:

  • 请选择地名

    我有一个疑问。。这将支持angular 2“*ngIf=“formSubmitted&&!myform.controls['placename'].valid“???????因为我只使用angular 2…我想在angular 2中支持这一点…非常感谢您的帮助