This article will show how you can fix the issue “Object is possibly ‘null’” Error in Angular Reactive Form Validation.
If you are using Angular v10 or above, you might encounter the “Object is possibly ‘null'” error in Angular reactive form validations, particularly when accessing the errors property of a form control. This error is a TypeScript compile-time error introduced with the strict mode enabled by default in Angular applications.
What is Object is possibly ‘null’ Error?
Object is possibly ‘null’ is a TypeScript compile-time error designed to identify potential null objects before runtime. With Angular v10 and above, TypeScript strict mode is enabled by default, which leads to more robust code but can also result in this specific error.
In your Angular application directory, you can find the tsconfig.json
file, where under compilerOptions
, the "strict": true
option enforces strict mode.
"compilerOptions": { "strict": true, // Other options... }
Three Ways to Fix Object is Possibly ‘null’ Error
There are three recommended ways to address the “Object is possibly ‘null'” error in Angular applications:
Solution 1: Disable Strict Mode
While the simplest way is to disable strict mode, it’s not recommended due to the loss of type safety. Open the tsconfig.json
file and set the value of strict
to false
.
"compilerOptions": { "strict": false, // Other options... }
Avoid using this solution unless absolutely necessary, as strict mode provides valuable type checking.
Solution 2: Using (!) Not Null Assertion Operator
If you are certain that an object can never be null, use the not null assertion operator !
. When accessing formGroup properties, apply the assertion operator to avoid the compile-time error.
<span class="text-danger" *ngIf="profileForm.get('firstName')!.errors && profileForm.get('firstName')!.hasError('required')">* Required</span>
Be cautious with this approach. If the property does not exist and you use the not null assertion operator, you may encounter runtime errors.
Solution 3: Using (?) Optional Chaining Operator
For a safer approach when unsure whether the object is null or not, use the optional chaining operator ?
. This ensures that even if the property does not exist, there won’t be any runtime errors.
<span class="text-danger" *ngIf="profileForm.get('firstName')?.errors && profileForm.get('firstName')?.hasError('required')">* Required</span>
This is considered the safest way to handle the “Object is possibly ‘null'” error in Angular reactive form validations.
Remember to make corresponding changes in your code based on the chosen solution.