如何验证&显示错误消息 - Angular2材料设计?

时间:2016-08-18 13:24:58

标签: angular typescript material-design angular-material

我有这个输入:

<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-invalid类:

enter image description here

enter image description here

当我填写一些内容时: enter image description here

Angular在其中注入ng-valid类。 enter image description here

我想要的是类似于angular1 md design的样式,如下所示:

enter image description here

3 个答案:

答案 0 :(得分:9)

希望这会在angular2-material演变时添加,但目前模仿它的方法是设置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>

答案 1 :(得分:3)

现在可以使用Angular Material版本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>

答案 2 :(得分:0)

在全局输入时显示 mat-error

1- 导入库:

import { ErrorStateMatcher, ShowOnDirtyErrorStateMatcher } from '@angular/material/core'; 

2- 添加到供应商,如:

@NgModule({
  providers: [
    AuthService,
    UserService,
    { provide: ErrorStateMatcher, useClass: ShowOnDirtyErrorStateMatcher }
  ],
})

3- 重新提供应用程序。