Search code examples
angulartypescriptangular11

In angular 11 material UI I am getting error TS2531: Object is possibly 'null' in my html template


I am using material UI and reactive form. My application is running properly and I am able to login but in my terminal window i am getting error TS2531: Object is possibly 'null'. I have attache the error screen shot below for the reference and also my login html template and component.

My login.component.html code is

<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>

My login.component.ts code is

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)
        }
      });
  }
}

My application is running properly but in terminal I am getting below error

Error

can someone please help


Solution

  • So, initially loginForm is undefined. Try to add loginForm?.control?...

    The same with error, by default there no errors,

    Also should add: errors?.required