mat-error 不显示错误消息 angular 5

mat-error not displaying error message angular 5

问题是即使我将字段留空并移至另一个字段,也不会显示错误消息。我在这里找不到我做错了什么。任何帮助将不胜感激。如果我在 onFormValuesChanged() 上设置断点,它永远不会到达断点。我试过在构造函数中移动表单的构建部分,但没有任何影响。我不确定字段值更改时是否触发表单的值更改事件

angular 版本:- 5.2.1

HTML代码

   <div>
    <form [formGroup]="formPersonalRecord">
    <mat-input-container class="full-width-input">
    <input matInput placeholder="First Name" formControlname="firstName">
      <mat-error *ngIf="formErrors.firstName.required">
      Please provide name.
      </mat-error>
     </mat-input-container>
     <mat-input-container class="full-width-input">
     <input matInput placeholder="Last Name" formControlname="lastName">
     </mat-input-container>
      <mat-input-container class="full-width-input">
      <input matInput placeholder="Father's Name" formControlname="fatherName">   
     </mat-input-container>
     <mat-input-container class="full-width-input">
      <input matInput placeholder="Email" formControlname="email">
       <mat-error *ngIf="formErrors.email.required">
        Please provide a email name.
       </mat-error>
     </mat-input-container>
    </form>
    </div>

component.cs

import { Component, OnInit } from '@angular/core';
import { EmployeePersonalRecord } from '../employee/employee-personal-record';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { fuseAnimations } from '../../core/animations';
import { HrService } from '../hr.service';



@Component({
  // tslint:disable-next-line:component-selector
  selector: 'app-add-employee',
  templateUrl: './add-employee.component.html',
  styleUrls: ['./add-employee.component.scss'],
  animations: fuseAnimations
})

export class AddEmployeeComponent implements OnInit {

  employeePersonalRecord:   EmployeePersonalRecord     = {} as EmployeePersonalRecord;
  public formPersonalRecord:       FormGroup;
  formErrors: any;
  constructor(private builder: FormBuilder,
    private service: HrService) {
  }

  onFormValuesChanged()
  {
    for ( const field in this.formErrors )
        {
            if ( !this.formErrors.hasOwnProperty(field) )
            {
                continue;
            }
            // Clear previous errors
            this.formErrors[field] = {};
            // Get the control
            const control = this.formPersonalRecord.get(field);
            if ( control && control.dirty && !control.valid )
            {
                this.formErrors[field] = control.errors;
            }
        }
  }

  ngOnInit() {
    this.formPersonalRecord = this.builder.group({
      firstName:              ['', Validators.required],
      lastName:               ['', Validators.required],
      email:                  ['', Validators.required],
      fatherName:             ['', Validators.required],
      dateOfBirth:            ['', Validators.required],
      addressPermanent:       ['', Validators.required],
      addressCurrent:         ['', Validators.required],
      gender:                 ['', Validators.required],
      maritalStatus:          ['', Validators.required],
      religion:               ['', Validators.required],
      cast:                   ['', Validators.required]
    });

    this.formErrors = {
      firstName:        {},
      lastName:         {},
      email:            {},
      fatherName:       {},
      dateOfBirth:      {},
      addressPermanent: {},
      addressCurrent:   {},
      gender:           {},
      maritalStatus:    {},
      religion:         {},
      cast:             {}
    };
    this.formPersonalRecord.valueChanges.subscribe(() => {
      this.onFormValuesChanged();
    });
  }
}

您的 formControlname 有错字。它的 formControlName 大写 N.

forked stackblitz

建议:

你不应该在 mat-error 上添加 *ngIf。垫错误的重点是避免做这样的事情。

你应该使用 mat-form-field 组件来包装你的输入

所以你可以简单地尝试一下:

<form [formGroup]="formPersonalRecord">
    <mat-form-field class="full-width-input">
       <input matInput placeholder="First Name" formControlName="firstName" />
          <mat-error>
                Please provide name.
          </mat-error>
    </mat-form-field>
...

我看不到任何 ErrorStateMatcher? 你应该使用它。

这是 material 文档的 stackblitz,输入使用了 errorstatematcher:https://stackblitz.com/angular/voepaombnnb

这可能晚了,但我遇到了同样的问题,发现我必须先将我的输入 [formControl] 绑定到 formGroup,然后才能像这样获取 formControl :

<form [formGroup]="formPersonalRecord">

 <mat-input-container class="full-width-input">
   <input matInput placeholder="First Name" [formControl]="formPersonalRecord.get('firstName')">
   <mat-error *ngIf="formPersonalRecord.get('firstName').hasError('required')">
      Please provide name.
   </mat-error>
 </mat-input-container>

此外,mat-error 在触摸控件(模糊)或提交表单之前不会显示。

我在 mat-error( "updateValueAndValidity" 解决了这个问题) 在此示例中,我在 mat-error.

中显示了异步错误消息
    onSubmit() {
    this.formSub = this.authenticationService
      .forgotPassword(this.resetForm.get('email').value).subscribe(
        next => {

        }, error => {
          console.log(error);
          this.resetForm.get('email').updateValueAndValidity();
          if (error[0] === 'USER_NOT_FOUND') {
            const passwordForm = this.resetForm.get('email');
            if (passwordForm) {
              passwordForm.setErrors({
                serverError: 'Email not found!'
              });
            }
          }
        }
      )
  }

<mat-error> 内容仅在触摸控件或提交表单时显示。 *ngIf条件可以指定,不是问题。 要显示 <mat-error> 内容,例如当您单击另一个按钮而不是提交按钮时,只需在按钮的处理程序中将所需的控件标记为已触摸:

onMyButtonClick() {
  this.form.get('myControl').markAsTouched();
  ...
}

另一种在不受Angular有效性管理约束的情况下显示消息的方法是使用<mat-hint>而不是<mat-error>

我认为最好的选择是使用:

updateValueAndValidity({ onlySelf: false, emitEvent: true })

如果您使用onlySelf = true,则无需将"markAsTouched"置于您的控制之下并适用于所有场景!