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

cha*_*ana 5 material-design angular 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>
Run Code Online (Sandbox Code Playgroud)

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();
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

Pie*_*let 16

你有一个关于formControlname的拼写错误.它的formControlName大写为N.

分叉的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>
...
Run Code Online (Sandbox Code Playgroud)

  • **您不应在错误时添加* ngIf。**这取决于情况。如果给定字段有多个错误消息(例如,必填,格式无效,没有电子邮件地址等),则matinput保证只正确显示1条消息。在这种情况下,您需要将* ngIF与mat-error一起使用 (6认同)
  • 哈哈Google真是个巨魔。他们的第一个也是唯一的示例显示了* ngIf,并且我一直在假设需要* ngIf的情况下进行编码。文字确实说“如果需要显示不同的错误消息,可以使用`* ngIf`”,但是代码示例只有一个“ mat-error”。zzz。非常感谢您让人们知道“ mat-error”可以在“ mat-form-field”下单独使用!会节省很多时间:) https://material.angular.io/components/form-field/overview#error-messages (3认同)

小智 9

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

onMyButtonClick() {
  this.form.get('myControl').markAsTouched();
  ...
}
Run Code Online (Sandbox Code Playgroud)

在没有任何与 Angular 有效性管理相关联的约束的情况下在控件下显示消息的另一种方法是使用<mat-hint>代替<mat-error>


Gou*_*ouk 7

这可能已经晚了,但是我遇到了同样的问题,发现我必须先将输入[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>
Run Code Online (Sandbox Code Playgroud)


Stu*_*ows 5

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

  • 这就是我不喜欢的。我需要在击键时显示错误。 (8认同)