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

时间:2018-01-25 12:53:35

标签: angular material-design angular5

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

角度ver: - 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();
    });
  }
}

7 个答案:

答案 0 :(得分:9)

你在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>
...

答案 1 :(得分:5)

这可能已经晚了,但是我遇到了同样的问题,发现在像这样获取formControl之前,我必须先将输入[formControl]绑定到formGroup上:

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

答案 2 :(得分:2)

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

答案 3 :(得分:1)

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

以下是材料doc的stackblitz,输入使用errorstatematcher:https://stackblitz.com/angular/voepaombnnb

答案 4 :(得分:1)

我在显示错误信息时遇到问题( 而“ 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!'
              });
            }
          }
        }
      )
  }

答案 5 :(得分:1)

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

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

在不受控制的情况下显示消息的另一种方法是与Angular有效性管理无关,这是使用<mat-hint>而不是<mat-error>

答案 6 :(得分:0)

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

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

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