Vicheanak Vicheanak - 11 months ago 349
AngularJS Question

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

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

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:

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

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

enter image description here

Answer Source

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:

          <md-input placeholder="Email address"
                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>