首页 > 解决方案 > 在 Angular 11 材质 UI 中,我收到错误 TS2531: Object is possible 'null' in my html template

问题描述

我正在使用材质 UI 和反应形式。我的应用程序运行正常并且可以登录,但在终端窗口中出现错误 TS2531:对象可能为“空”。我附上了下面的错误屏幕截图以供参考,以及我的登录 html 模板和组件。

我的 login.component.html 代码是

<div class="example-container">
  <div class="form-container">
    <form [formGroup]="loginForm" (submit)="onSubmit()">
      <mat-form-field class="form-field" appearance="outline">
        <mat-label> E-mail
        </mat-label>
        <input matInput formControlName="email" required>
        <mat-error *ngIf="loginForm.controls.email.touched && loginForm.controls.email.invalid">
          <span *ngIf="loginForm.controls.email.errors.required">This field is mandatory.</span>
          <span *ngIf="loginForm.controls.email.errors.pattern">This field is invalid.</span>
        </mat-error>
      </mat-form-field>
      <mat-form-field class="form-field" appearance="outline">
        <mat-label> Password
        </mat-label>
        <input matInput formControlName="password" type="password">
        <mat-error *ngIf="loginForm.controls.password.touched && loginForm.controls.password.invalid">
          <span *ngIf="loginForm.controls.password.errors.required">This field is mandatory.</span>
        </mat-error>
      </mat-form-field>
      <button mat-raised-button color="primary" type="submit">Log In</button>
    </form>
  </div>
</div>

我的 login.component.ts 代码是

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { first } from 'rxjs/operators';
import { NotificationService } from 'src/app/_services';
import { AuthService } from '../auth.service';
import { Login } from '../user';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  loginForm!: FormGroup;
  loading = false;
  submitted = false;
  error = '';
  emailRegx = /^(([^<>+()\[\]\\.,;:\s@"-#$%&=]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,3}))$/;


  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private authService: AuthService,
    private router: Router,
    private notifyService: NotificationService
  ) {
  }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      email: ["", [Validators.required, Validators.pattern(this.emailRegx)]],
      password: ["", Validators.required]
    });
  }

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

  onSubmit() {

    this.submitted = true;

    if (this.loginForm.invalid) {
      return;
    }

    this.loading = true;

    let login: Login = { Email: this.f.email.value, Password: this.f.password.value }

    this.authService.signIn(login)
      .pipe(first())
      .subscribe({
        next: () => {
          this.router.navigateByUrl('/landing');
        },
        error: error => {
          this.error = error;
          this.loading = false;
          this.notifyService.showError(this.error, this.error)
        }
      });
  }
}

我的应用程序运行正常,但在终端中出现以下错误

错误

有人可以帮忙吗

标签: angulartypescriptangular11

解决方案


所以,最初loginForm是未定义的。尝试添加loginForm?.control?...

与错误相同,默认没有错误,

还应补充:errors?.required


推荐阅读