首页 > 解决方案 > Angular 表单验证未显示在 Angular 表单错误中

问题描述

这是我的 HTML

 <form [formGroup]="applicationDetailsForm" (ngSubmit)="appDetails(applicationDetailsForm.value)">
    <label>Organization Name</label>
      <input type="text" formControlName="appName" id="appName" required>
      <p class="error_message" *ngIf="
      applicationDetailsForm.get('appName').hasError('required') 
      && applicationDetailsForm.get('appName').touched 
      && applicationDetailsForm.get('appName').minLength 
      && applicationDetailsForm.get('appName').maxLength">Provide a valid name</p>

这是我的组件

ngOnInit() {
    this.applicationDetailsForm = this.formBuilder.group({
      appName: new FormControl ('', Validators.compose([Validators.required, Validators.maxLength(32), 
        Validators.minLength(4)]))
})

表格中的错误没有显示出来。请帮忙!

标签: angularformsvalidationangular-reactive-formsangular-forms

解决方案


您正在测试minLength && maxLength您的状况以显示错误消息。他们永远不会同时处于活动状态。

您也没有正确查找minLength&maxLength错误。它们不是FormControl自身的直接属性——它们是errors子属性。

你可能会有更好的运气:

*ngIf="
    applicationDetailsForm.get('appName').touched && (
        applicationDetailsForm.get('appName').hasError('required') 
        || applicationDetailsForm.get('appName').hasError('minLength')
        || applicationDetailsForm.get('appName').hasError('maxLength')
    )
"

还可以考虑采用通过 getter访问Angular 的最佳实践:FormControl

  • component.ts

    get appName() { return this.applicationDetailsForm.get('appName'); }
    
  • component.html

    <form [formGroup]="applicationDetailsForm" (ngSubmit)="appDetails(applicationDetailsForm.value)">
        <label>Organization Name</label>
          <input type="text" formControlName="appName" id="appName" required>
          <p class="error_message" *ngIf="appName.touched && (
              appName.errors.required
              || appName.errors.minLength
              || appName.errors.maxLength
          )">Provide a valid name</p>
    

推荐阅读