typescript 如何验证和显示错误消息 - Angular2 Material Design?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39019430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:45:45  来源:igfitidea点击:

How to Validate & Display Error Message - Angular2 Material Design?

angulartypescriptmaterial-designangular-material

提问by Vicheanak

I have this input:

我有这个输入:

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

But the message Price is required doesn't show up.

但是没有显示需要价格的消息。

How should I properly format the error message?

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

The ng-invalid class appears when the price input is empty:

当价格输入为空时出现 ng-invalid 类:

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

When I fill in something: enter image description here

当我填写一些东西时: 在此处输入图片说明

Angular injects ng-valid class in it. enter image description here

Angular 在其中注入了 ng-valid 类。 在此处输入图片说明

I want is to have the style similar to angular1 md designthat looks like this:

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

enter image description here

在此处输入图片说明

回答by user1558224

Hopefully this will be added as angular2-material evolves, but currently the way to mimic this is to set the dividerColor and use the MD-HINT directive. example:

希望这将随着 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>

回答by Dilshan Liyanage

Validation messages can now be inserted with Angular Material version 2.0.0 onward. Check the documentation here.

现在可以使用 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>