2016-07-25 127 views
3

我正在寫angular2中的表單驗證。 我的錯誤是Cannot read property 'valid' of undefined角度2中的表單驗證

我的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

使用

[hidden]="contact.controls['author'].valid" 
+0

爲什麼?哪裏有什麼區別?任何參考? – dakab

+0

您需要在''中添加'#author ='ngForm''來使'[hidden] =「author.valid」工作,導致類似「檢查後表達式被改變」的錯誤。或者,您可以創建一個變量'author = new Control(',[Validators.required]);'並將其添加到'this._formBuilder.group({'author':this.author})'',然後您的視圖綁定也應該起作用。我也建議你遷移到新的表單模塊。沒有意義投入時間學習已經被取代的東西。 –