30

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.

12 Answers 12

65

The object f.firstName.errors can be null. Use the safe navigation operator ?:

*ngIf="f.firstName.errors?.required"
Sign up to request clarification or add additional context in comments.

4 Comments

Or f.firstName.hasError('required') or f.hasError('required', 'firstName').
wow this must be a new addition to the latest angular I never had this issue in the past years! thanks for pointing this out!
@d0rf47 this is because u op have strict mode on.
@developer033 your comment should be an own answer! I would upvote too! Thank you!
11

For angular version ^14.0, this can be used:

form.controls['firstName'].errors?.['required']
and 
form.controls['firstName'].errors?.['minlength']

Comments

9

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"

1 Comment

For some reason in the required one I had to put the question mark (?) in firstName and in errors for it to work
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.

1 Comment

Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?
2

<div *ngIf="postForm.get('title')?.touched && !postForm.get('title')?.valid"> <div *ngIf="postForm.get('title')?.errors?.['required']" class="alert alert-warning"> Title is required </div> </div> angular version is 13.3.0 5

The Object is possibly 'null' error can happen due to strict type checking and can be solved in 2 ways:

  • Either assert that you are absolutely sure that can never be null, by using the ! (not null assertion operator)
  • Use the ? (optional chaining operator) to stop an eventual error from happening in case the object is indeed null

So you can replace the if statement with postForm.get('title')?.touched && !postForm.get('title')?.valid and it should work.

Comments

2

This is what worked for me in 2023:

In tsconfig.json, I just changed "strict": true, to "strict": false, and restarted the server.

The above fixed it for me.

2 Comments

This is not something recommended though.
The word "fixed" should be replaced with "workaround"...
1

We can us form.controls['firstName] and form.controls['firstName].errors?.length

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
1

// Property 'requiered' comes from an index signature, so it must be accessed with ['requiered'].ngtsc(4111)

solutions: <div *ngIf="f?.errors?.['requiered']">

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

Latest Angular Syntax require safe navigation operator ? in brackets as shown below:

*ngIf="f['firstname'].errors?['required']"

Comments

0

Validation for a required field

<input type="text" class="form-control form-control-user" formControlName="firstname">
<div class="text-danger" *ngIf="(f['firstname'].touched || submitted) && f['firstname'].errors?.['required']"> First Name is required!</div>

Comments

0

You can also use 'non-null assertion operator' which is used if the typescript compiler complains about a value being null or undefined , you can use the ! operator to assert that the said value is not null or undefined .

*ngIf="cardForm.controls.name.errors!['required']"

Comments

-1

error TS2531: Object is possibly 'null'.

4 <div class="alert alert-danger" *ngIf="myForm.get('fname').touched">

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.