2016-12-14 29 views
-1

如何通過Angular2 FormsModule使這些輸入在提交時顯示消息,例如「Name is required」(因此提交按鈕被禁用,直到名稱內部爲止)?如何在Angular 2中實現表單輸入驗證

<form class=""> 
    <div> 
     <p>Name:</p> 
     <input type="text"> 
    </div> 
    <div class="link-input"> 
     <p>City:</p> 
     <input type="text"> 
    </div> 

    <button 
     (click)="submitForm()"> 
     Submit 
    </button> 
</form> 
+0

https://開頭的角.io/docs/ts/latest/cookbook/form-validation.html – ranakrunal9

+0

[https://angular.io/docs/ts/latest/guide/forms.html](https://angular.io/docs/ts/latest/guide/forms.html) – PierreDuc

回答

2

按照此示例:

<form [formGroup]="registerForm" (ngSubmit)="submitForm(registerForm)" novalidate> 
    <div> 
     <p>Name:</p> 
     <input type="text"> 
     </div> 
     <div class="link-input"> 
      <p>City:</p> 
      <input formControlName="username" type="text"> 
       <em for="username" [hidden]="showError(registerForm.controls.name)" class="invalid">  You left this field blank or email format is not correct</em> 

      </div> 

      <button type="submit" >Submit</button> 
</form> 

組件:

showError(field: FormControl){ 
     if(!field) 
      return true; 
     return field.valid || (field.pristine && !field.touched && !this.submitted) 
    } 

submitForm(f: NgForm) { 
    this.submitted = true; 
    if(!f.valid) 
     return; 
} 
+0

謝謝你的回答。我想要做的是使窗體驗證模板驅動,是否有一個簡單的方法來做到這一點..?對不起,如果我不清楚首先。據我所知,我需要在現有的表單結構中添加一些屬性,併爲應用程序組件中的功能製作函數。此外,我的應用程序組件應該只導入FormsModule(而不是FormGroup,FormControl等),所以我需要一種方法來做到這一點,沒有這兩個導入 – Smithy

0

只需添加檢查的形式是有效的,否則禁用按鈕

<button type="submit" class="btn btn-danger" [disabled]="!f.valid">Save to List</button> 
相關問題