首页 > 解决方案 > 角度反应形式不显示错误消息

问题描述

我的反应式表单(Angular 11)出现错误。

当我想在我的输入电子邮件和密码尚未设置时显示错误消息,但我有一个错误 对象可能为空

我的 login.component.html

<div class="row mt-5">
    <div class="col-md-6 mx-auto">
      <form [formGroup]="loginForm">
  
        <div class="form-group">
          <label for="email">Email</label>
          <input
            formControlName="email"
            type="text"
            class="form-control"
            id="email"
            required
          >
  
          <div Class="text-danger">
            <div *ngIf="loginForm.get('email').hasError('required')">Email is Required !</div>
          </div>
        </div>
  
        <div class="form-group">
          <label for="password">Password</label>
          <input
            formControlName="password"
            type="password"
            class="form-control"
            id="password"
            required
          >
  
          <div Class="text-danger" >
            <div *ngIf="loginForm.get('password').hasError('required')">Password is Required !</div>
            <div *ngIf="loginForm.get('password').hasError('minlength')">Password was to be 8 Caracters !</div>
          </div>
        </div>
        {{loginForm.value | json}}
        <button [disabled]="loginForm.invalid" class="btn btn-primary btn-block">Sign In</button>
      </form>
    </div>
  </div>

我的 login.component.ts

loginForm: FormGroup ;

  constructor() { }

  ngOnInit(): void {
    this.loginForm = new FormGroup({
      email: new FormControl(null, [Validators.required]),
      password: new FormControl(null, [Validators.required, Validators.minLength(8)])
    });
  }

  get email() { return this.loginForm.get('email'); }

  get password() { return this.loginForm.get('password'); }

你能告诉我为什么我没有收到错误消息并且我有编译错误,称为Object is possible null。在 app.module.ts 文件中,我在导入部分有 formsModule 和 ReactiveModule。

标签: angulartypescriptangular-forms

解决方案


Try like as this -

In your Component just create one function and remove both which you have created for each control - email and password.

 get inputRequired() { return this.loginForm.controls; }

In your HTML -

 <div *ngIf="inputRequired.email.errors" class="text-danger">
    <div *ngIf="inputRequired.email.errors.required">Email is Required !</div>
 </div>

I have just shown you for Email, similarly you can do it for Password field too.


推荐阅读