我正在尝试创建一个简单的Angularjs表单,并且在我第一次导航到视图时无法隐藏表单错误。我希望仅在用户单击“继续”按钮时显示错误消息。这是组件html代码:
<section class="testApp">
<form [formGroup]="signUpForm" (ngSubmit)="onSubmit(signUpForm.value)" >
<div class="container">
<div class="row">
<div class="col-md-2"></div>
<header class="header col-md-8">
<h1>Data Entry</h1>
</header>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<section class="main">
<div class="form-group">
<div class="form-text">*When were you born ?</div>
<input class="form-control" id="dob" type="date" [formControl]="signUpForm.controls['dob']">
<div class="alert alert-danger" *ngIf="signUpForm.controls['dob'].hasError('required')" >You must enter a date.</div>
</div>
<div class="form-group">
<div class="form-text">Question here ?</div>
<input type="radio" name="res" value="YES" [formControl]="signUpForm.controls['res']" > YES
<input type="radio" name="res" value="NO" [formControl]="signUpForm.controls['res']" > NO
<div class="alert alert-danger" *ngIf="signUpForm.controls['res'].hasError('required')">You must select an option.</div>
</div>
<div class="form-group">
<div class="form-text">*Some Important Question here ?</div>
<input type="radio" name="ins" value="YES" [formControl]="signUpForm.controls['ins']" > YES
<input type="radio" name="ins" value="NO" [formControl]="signUpForm.controls['ins']" > NO
<input type="radio" name="ins" value="Unsure" [formControl]="signUpForm.controls['ins']" > I'M NOT SURE
<div class="alert alert-danger" *ngIf="signUpForm.controls['ins'].hasError('required') ">You must select an option.</div>
</div>
<div>
<button type="submit" >CONTINUE</button>
</div>
</section>
</div>
<div class="col-md-2"></div>
</div>
</div>
</form>
</section>
这是component.ts文件:
export class SignUpComponent {
signUpForm : FormGroup;
constructor(private _router: Router, fb: FormBuilder)
{
this.signUpForm=fb.group({
'dob': [null,Validators.compose([Validators.required, AgeValidator.Validate])],
'res': [null,Validators.required],
'ins': [null,Validators.required],
})
}
}[![By default errors showing up even when the form is not dirty.][1]][1]
答案 0 :(得分:1)
为表单添加novalidate:
<form [formGroup]="signUpForm" (ngSubmit)="onSubmit(signUpForm.value)" novalidate>
更新:
如果你想要反应性验证,你肯定需要novalidate
。
这是一个有效的plunker。