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

Vic*_*nak 5 typescript material-design angular-material angular

我有这个输入:

<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>
Run Code Online (Sandbox Code Playgroud)

但是需要消息价格不会出现.

我该如何正确格式化错误消息?

当价格输入为空时,将显示ng-invalid类:

在此输入图像描述

在此输入图像描述

当我填写一些东西: 在此输入图像描述

Angular在其中注入ng-valid类. 在此输入图像描述

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

在此输入图像描述

小智 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>
Run Code Online (Sandbox Code Playgroud)

  • 您可能想要编辑最新版本的答案.dividerColor现在需要成为md-input-container的一部分而不是md-input (2认同)

Dil*_*age 5

现在可以使用 Angular Material 版本 2.0.0 插入验证消息。在此处查看文档。

<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>
Run Code Online (Sandbox Code Playgroud)