代码之家  ›  专栏  ›  技术社区  ›  chanakya sankritayana

mat错误未显示错误消息角度5

  •  9
  • chanakya sankritayana  · 技术社区  · 8 年前

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

    角度版本:-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>
    

    组成部分反恐精英

    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 回复  |  直到 5 年前
        1
  •  26
  •   Pierre Mallet    8 年前

    formControlname上有一个输入错误。其formControlName以大写N表示。

    forked stackblitz

    建议:

    您不应添加*ngIf on mat error。mat错误的全部目的是避免这样做。

    您应该使用mat form字段组件来包装您的输入

    因此,您可以简单地尝试:

    <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>
    ...
    
        2
  •  12
  •   Nike Xfox    5 年前

    <mat-error> 仅当触摸控件或提交表单时,才会显示内容。 *ngIf 条件可以指定,但不是问题所在。 要显示 <mat错误(>); 内容例如,当您单击“提交”按钮以外的其他按钮时,只需在按钮的处理程序中将所需控件标记为已触摸:

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

    另一种在控件下显示消息的方法是使用 <mat-hint> 而不是 <mat错误(>);

        3
  •  8
  •   Gouk    7 年前

    这可能很晚了,但我也遇到了同样的问题,我发现在获取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>
    
        4
  •  6
  •   Stuart Hallows    6 年前

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

        5
  •  3
  •   Manon Ingrassia    8 年前

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

    以下是物料文档的stackblitz,输入使用errorstatematcher: https://stackblitz.com/angular/voepaombnnb

        6
  •  1
  •   Volodymyr Palchynskyy    6 年前

    我在mat错误中显示消息时遇到问题( “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!'
                  });
                }
              }
            }
          )
      }
    
        7
  •  0
  •   Andrey E    5 年前

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

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

    如果您使用 onlySelf = true ,您不需要 "markAsTouched" 在您的控制下,适用于所有场景!