首页 文章

Angular Material 2 - 处理多个验证错误消息

提问于
浏览
7

我正在使用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 .

2 回答

  • 4

    见下面的例子 . 获得工作示例的一个好方法是查看/搜索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>
    
  • 1

    这就是我在 Angular 6ReactiveFormsModule )中实现的方法

    HTML

    <form [formGroup]="service.form" class="normal-form">
     <mat-grid-list cols="2" rowHeight="300px">
        <mat-grid-tile>
        <input type="hidden" formControlName="$key">
          <div class="controles-container">
              <mat-form-field>
                <input formControlName="mobile" matInput placeholder="Mobile*">
                <mat-error *ngIf="service.form.controls['mobile'].errors?.required">This field is mandatory.</mat-error>
                <mat-error *ngIf="service.form.controls['mobile'].errors?.minlength">Minimum 8 charactors needed.</mat-error>
            </mat-form-field>      
          </div>
        </mat-grid-tile>
    </mat-grid-list>
    </form>
    

    Component.ts

    export class MyComponent implements OnInit {
    
      constructor(public service :EmployeeService) { }
    
      ngOnInit() {
      }
    
      onClear() {
        this.service.form.reset();
    
      }
    }
    

    Service

    export class EmployeeService {
    
      constructor() { }
    
      form :FormGroup = new FormGroup({
        $key :new FormControl(null),
        mobile:new FormControl('',[Validators.required,Validators.minLength(10)]),  
      });
    }
    

相关问题