我正在angular2中编写表单验证。
我的错误是Cannot read property 'valid' of undefined
我的HTML文件包含一个表单,即
<form id="commentform" class="comment-form" novalidate
[ngFormModel] = "contact" (ngSubmit)="submit(contact.value)">
<div class="form-input">
<input type="text" id="author" name="author" placeholder="Name *" value=""
[ngFormControl] = "contact.controls['author']" pattern="[a-zA-Z ]*"/>
<div [hidden]="author.valid">Name is required
</div>
</div>
我在div [hidden]="author.valid"
收到错误。
错误为Cannot read property 'valid' of undefined"
我的组件文件包含
import {FormBuilder ,ControlGroup,Validators } from '@angular/common';
@Component({
selector: 'my-contact',
templateUrl : 'app/contact.html'
}
export class ContactComponent {
contact : ControlGroup;
constructor(private _OnChange:OnChange,private _formBuilder : FormBuilder){
this.ngAfterViewInit();
}
ngOnInit() : any{
this.contact = this._formBuilder.group({
'author' : ['',Validators.required] }); }
submit(){
console.log(JSON.stringify(this.contact.value));
}
答案 0 :(得分:0)
使用
[hidden]="contact.controls['author'].valid"
答案 1 :(得分:0)
因为作者不是变量。使用
<div [hidden]="contact?.controls?.author?.valid">Name is required</div>
实际上,甚至更好。你应该使用新的表单模块 @ angular / forms https://scotch.io/tutorials/using-angular-2s-model-driven-forms-with-formgroup-and-formcontrol