2016-08-18 89 views
5

我有這個輸入:如何驗證並顯示錯誤消息 - Angular2 Material Design?

<form #f="ngForm" name="productForm"> 
    <md-input [(ngModel)]="product.price" name="price" required="true" placeholder="Price (USD)"></md-input> 
    <div ng-messages="productForm.price.$error" role="alert"> 
     <div ng-message-exp="['required']"> 
       Price is required 
      </div> 
    </div> 
</form> 

但該消息的價格要求不出來。

我應該如何正確格式化錯誤信息?

當價格輸入爲空,出現NG-無效類:

enter image description here

enter image description here

當我填寫的東西: enter image description here

角內噴射NG-有效類它。 enter image description here

我要的是有一個看起來像這樣的類似angular1 md design風格:

enter image description here

回答

9

希望這將作爲angular2材料的發展,但目前的方式來模仿這是設置dividerColor並使用MD-HINT指令。例如:

<md-input placeholder="Email address" 
    #email="ngModel" 
    name="email" 
    type="text" 
    fullWidth={true} 
    [(ngModel)]="model.email" 
    required 
    email 
    dividerColor="{{ !email.valid ? 'warn' : 'primary' }}"> 
    <md-hint [hidden]="email.pristine || email.valid"> 
     <span [hidden]="email.errors?.required || !email.errors?.email"> 
      This doesn't appear to be a valid email address. 
     </span> 
     <span [hidden]="!email.errors?.required">Email address is required.</span> 
    </md-hint> 
</md-input> 
+0

對不起,你是什麼意思,!email.errors?.email? – Vicheanak

+0

關於這一個的討論在官方材料2回購https://github.com/angular/material2/issues/348 – Kuncevic

+2

您可能想要編輯最新版本的答案。 dividerColor現在需要成爲md-input-container的一部分而不是md-input – cport1

3

驗證消息現在可以插入角度材質版本2.0.0以上版本。檢查文檔here

<form class="example-form"> 
    <mat-form-field class="example-full-width"> 
    <input matInput placeholder="Email" [formControl]="emailFormControl"> 
    <mat-error *ngIf="emailFormControl.hasError('pattern')"> 
     Please enter a valid email address 
    </mat-error> 
    <mat-error *ngIf="emailFormControl.hasError('required')"> 
     Email is <strong>required</strong> 
    </mat-error> 
    </mat-form-field> 
</form> 
+0

是否可以在輸入時顯示錯誤,而不是在輸入字段模糊時顯示。我知道,如果我模糊它,然後鍵入它會驗證我鍵入,但它有可能讓我在輸入第一次輸入字段時輸入錯誤信息? –

相關問題