'Error TS2531 object is possibly null in angular reactive forms
Hi i have tried to do reactive form validation in angular 11 but its showing following error in terminal.
error TS2531 object is possibly null.
my code in signup.component.ts
import {FormGroup, FormControl, Validators} from '@angular/forms';
form = new FormGroup({
firstName: new FormControl('',Validators.required)
})
get f()
{
return this.form.controls;
}
in signup.component.html
<form role="form" [formGroup]="form">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" formControlName="firstName" [ngClass]="{'is-invalid':form.get('firstName').touched && form.get('firstName').invalid}">
<div *ngIf="f.firstName.touched && f.firstName.invalid">
<small class="text-danger" *ngIf="f.firstName.errors.required">
Name is required!
</small>
</div>
</div>
</form>
when i run its showing error in
<small class="text-danger" *ngIf="f.firstName.errors.required"> Name is required!
error TS2531 object is possibly null.
Solution 1:[1]
latest version of angular requires you Use the safe navigation operator inside your first if check as well eg.
*ngIf="f.firstName?.touched && f.firstName?.invalid"
then finally
*ngIf="f.firstName.errors?.required"
Solution 2:[2]
We can us form.controls['firstName] and form.controls['firstName].errors?.length
Solution 3:[3]
Latest Angular Syntax require safe navigation operator ? in brackets as shown below:
*ngIf="f['firstname'].errors?['required']"
Solution 4:[4]
<div *ngIf="f.firstName?.touched && f.firstName?.invalid">
<small class="text-danger" *ngIf="f.firstName?.errors?.['required']">
Doing validation in reactive form Angular 13 requires to add optional chaining operator (the question mark '?') to the FormControl object (f.firstName) and its errors property.
Solution 5:[5]
error TS2531: Object is possibly 'null'.
4 <div class="alert alert-danger" *ngIf="myForm.get('fname').touched">
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | VÃtor França |
| Solution 2 | Saswati Choudhury |
| Solution 3 | ahuemmer |
| Solution 4 | |
| Solution 5 | Sab Rina Balti |
