我正在使用Angular Material 2创建一个表单.我使用模板驱动的表单,我有电子邮件输入,有两个验证器(必需和电子邮件).在输入组件的文档(
https://material.angular.io/components/component/input)中,它只说:
“如果输入元素可以有多个错误状态,则由消费者决定应该显示哪些消息.这可以通过CSS,ngIf或ngSwitch来完成.”
没有例子,我无法在任何地方找到它.
这是我的HTML:
... <form (ngSubmit)="onSubmit(registrationForm)" #registrationForm="ngForm"> ... <md-input-container floatPlaceholder="never"> <input mdInput type="email" placeholder="Enter your email address" name="email" [(ngModel)]="email" required email> <md-error class="required">Email is required.</md-error> <md-error class="email">Invalid email.</md-error> </md-input-container> ...
任何提到的解决方案(CSS,ngIf或ngSwitch)都可以,但我更喜欢CSS.
见下面的例子.获得工作示例的一个好方法是查看/搜索Angular 2 Material GIT仓库.以下示例来自
https://github.com/angular/material2/blob/master/src/demo-app/input/input-demo.html
<md-input-container> <input mdInput placeholder="email" [formControl]="emailFormControl"> <md-error *ngIf="emailFormControl.hasError('required')"> This field is required </md-error> <md-error *ngIf="emailFormControl.hasError('pattern')"> Please enter a valid email address </md-error> </md-input-container>