Reactive Forms: Validation

ngIf="form.get(‘username’).touched

This gives me an error message: “Object is possibly ‘null’”

It does not like the “touched” portion of this code or the “invalid” portion. I get the same error for both.

It looks like you must be using a more recent version of TypeScript / Angular which has probably opted you into strict null safety. In order to do this, you need to use the ?. operator instead of simply using . which will handle the null safety for you:

<div *ngIf="form.get('username')?.touched"> ... </div>
1 Like

That fixed the problem… however I get the same issue when creating the specific error validators… So I used the ? operator on “username” and it fixes the issue with username.errors where errors is possibly null.

*ngIf=“username?.errors.required”

However the required portion still throws an error… it will not let me add the ? operator on both elements… "username?.errors?.required

I had this problem in Sec 7, with Template validators, as well but I skipped over it because i couldn’t solve the problem.

I am using:
typescript 4.6.4
angular cli 13.3.5
node js 16.15.0
npm 8.10.0

In my IDE (VSCode) it gave me this helpful warning message which pointed me at what I needed to do:

Property ‘required’ comes from an index signature, so it must be accessed with [‘required’].

Which means doing stuff like this:

<div *ngIf="username.errors?.['required']">...</div>

This actually matches what the Angular documentation says about validating input in template-driven forms. According to some Stackoverflow answers, it looks like this behavior changed in Angular v13 (which you are using).

1 Like

I did everything you said, but I still get the “Object is possibly null” error. Here is my code:

  <div *ngIf="username?.touched && username?.invalid" class="alert alert-danger">
        <div *ngIf="username.errors?.['required']"> Username is required </div>
        <div *ngIf="username.errors?.['minlength']">Username should be minimum 3 characters</div>
        <div *ngIf="username.errors?.['cannotContainSpace']"> Username should not have any spaces</div>
      </div>