angularangular-reactive-formsangular2-formsangular-abstract-control

Angular Error: Type 'AbstractControl | null' is not assignable to type 'AbstractControl'


I tried to fix this problem with an $any(), but I don't think I did it correctly. Could someone help me with this error, please?

The error occurs on these lines of code:

get email(): AbstractControl { return this.loginForm.get('email')}

get password(): AbstractControl { returnthis.loginForm.get('password')}

Code provided below:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';

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

  loginForm!: FormGroup;
  emailPattern = /^(([^<>()\[\]\\.,;:\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,}))$/

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.initForm();
  }

  initForm() {
    this.loginForm = this.fb.group({
      email: ['', [Validators.required, Validators.pattern(this.emailPattern)]],
      password: ['', [Validators.required, Validators.minLength(6)]]
    });
  }

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

    
    alert(this.diagnostic);
  }

  get email(): AbstractControl { return this.loginForm.get('email')}
  get password(): AbstractControl { return this.loginForm.get('password')}

  get diagnostic(): string {
    return JSON.stringify(this.loginForm.value);
  }

}
<section id="login">
  <div class="bwm-form">
    <div class="row">
      <div class="col-md-5">
        <h1>Login</h1>
        <!-- <div *ngIf="notifyMessage" class="alert alert-success">
          Some message
        </div> -->
        <form [formGroup]="loginForm">
          <div class="form-group">
            <label for="email">Email</label>
            <input 
              formControlName="email"
              type="email"
              class="form-control"
              id="email">
            <div 
              *ngIf="email.invalid && !email.pristine"
              class="alert alert-danger">
              <div *ngIf="email.errors?.['required']">
                Email is required.
              </div>
              <div *ngIf="email.errors?.['pattern']">
                Must be valid email format!
              </div>
            </div>
          </div>
          <div class="form-group">
            <label for="password">Password</label>
            <input 
              formControlName="password"
              type="password"
              class="form-control"
              id="password">
            <div 
              *ngIf="password.invalid && !password.pristine"
              class="alert alert-danger">
              <div *ngIf="password.errors?.['required']">
                Password is required.
              </div>
              <div *ngIf="password.errors?.['minlength']">
                Minimum length of password is 6 characters.
              </div>
            </div>
          </div>
          <button 
            (click)="login()"
            [disabled]="loginForm.invalid"
            type="submit" 
            class="btn bwm-btn-main">Submit</button>
        </form>
        <!-- <div *ngIf="errors.length > 0" class="alert alert-danger">
          <p *ngFor="let error of errors">
            {{error.detail}}
          </p>
        </div> -->
      </div>
      <div class="col-md-6 ml-auto">
        <div class="image-container">
          <h2 class="catchphrase">Hundreds of awesome places in reach of few clicks.</h2>
          <img src="assets/images/login-image.jpg" alt="">
        </div>
      </div>
    </div>
  </div>
</section>


Solution

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

    this.loginForm.get('email'); returns AbstractControl<ɵGetProperty<TRawValue, P>> | null, so it can be AbstractControl or null. See here.

    The problem is that you defined get email() as AbstractControl and not as AbstractControl | null.