我正在尝试验证Angular反应形式,我试图在其中捕获输入字段的值,如果未验证输入字段,我将显示消息
<span *ngIf="signupForm.control['fname'].haserror(required) && signForm.control['fname'].invalid && signForm.control['fname'].touched "> Enter your Name </span>
..但是我遇到 错误->
ERROR TypeError: Cannot read property 'fname' of undefined
我将填写表格的所有详细信息
html代码-
<form [formGroup]='signupForm' (ngSubmit)="PostData(signupForm)">
<h2 class="text-center"> Registeration Form </h2>
<br/>
<div class="form-group">
<input type="text" formControlName='fname' placeholder="First Name">
<span *ngIf="signupForm.control['fname'].haserror(required) && signForm.control['fname'].invalid && signForm.control['fname'].touched "> Enter your Name </span>
</div>
<input type="submit" value="Post Data" [disabled]='!signupForm.valid'>
</div>
</form>
ts文件代码->
export class ReactiveComponent implements OnInit {
signupForm: FormGroup;
FirstName: string = '';
LastName: string = '';
Eamil: string = '';
Password: string = '';
constructor(public frmbuilder: FormBuilder) { // formBuilder assign all the formcontrol to formgroup
this.signupForm = frmbuilder.group({
fname: ['',Validators.compose([Validators.required , Validators.minLength(4)])], // FormControl Used to bring input value to the ts file
lname: ['', Validators.required],
Emailid: ['', [Validators.required , Validators.email]],
userpassword: ['', Validators.required ]
});
}
ngOnInit() {
}
PostData(signupForm: any) {
console.log(signupForm.controls);
this.FirstName = signupForm.controls.fname.value;
this.LastName = signupForm.controls.lname.value;
this.Eamil = signupForm.controls.Emailid.value;
this.Password = signupForm.controls.userpassword.value;
}
答案 0 :(得分:1)
应该是
存在错误始终在camelCase中
<span *ngIf="signupForm.get('fname').hasError(required) && signupForm.get('fname').invalid && signupForm.get('fname').touched "> Enter your Name </span>
答案 1 :(得分:0)
尝试
<span *ngIf="signupForm.controls['fname'].hasError('required')">Firstname is Required!! </span>
请注意您调用fname
控件的方式,请执行signupForm.controls
而不是signupForm.control