NaingMinZaw
NaingMinZaw

Reputation: 101

error TS2531 Object is possibly 'null' in angular reactive forms

I try angular reactive form validation and template driven form validation,but reactive form validation show me an error like that ,null when I try to compile and run. My angular version is 10.0.14

So, I have the component.html

<form action=""
  [formGroup]="singupForm"
  (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label for="">Username</label>
      <input
      type="text"
      id="userName"
      class="form-control"
      formControlName="userName"
      >
      <span
      *ngIf="username.invalid"
      class="help-block"
      >Please enter valid username!</span>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>

following is the component.ts file

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

     @Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css'],
     })
    export class AppComponent implements OnInit{

    singupForm! : FormGroup;
    constructor(){}

    ngOnInit(){
     this.singupForm = new FormGroup({
     userName : new  FormControl(null, Validators.required)
     });
     }
       get username(){
        return this.singupForm.get('userName');
         }

         onSubmit(){
          console.log(this.singupForm.value)
         }

} app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
declarations: [
AppComponent,
],

imports: [
  BrowserModule,
  ReactiveFormsModule
],

   providers: [],
   bootstrap: [AppComponent]
   })
 export class AppModule { }

Error is just like that

   ERROR in src/app/app.component.html:16:27 - error TS2531: Object is 
   possibly 'null'.

   16           *ngIf="username.invalid"
                         ~~~~~~~ src/app/app.component.ts:6:16
   6   templateUrl: './app.component.html',
                 ~~~~~~~~~~~~~~~~~~~~~~
  Error occurs in the template of component AppComponent.

   ** Angular Live Development Server is listening on localhost:4200, open 
     your browser on http://localhost:4200/ **

Upvotes: 2

Views: 6168

Answers (2)

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19754

While your answer is correct in a sense that the error goes away and your application can compile, it does not address the problem, nor explains why it happens.

The core of the issue is, as the error message you've posted suggests, that the username property on the class could be null. This is how you define it:

get username () {
  return this.singupForm.get('userName')
}

Indeed, if you take a look at the implementation of FormGroup#get in Angular's source code, you'll see that the return type is AbstractControl | null just form the signature:

get (path: Array<string|number>|string): AbstractControl | null

So even though you know that in your case form.get('userName') will surely return an instance of FormControl, Angular cannot be sure that you didn't remove it in the meantime, or change its type to something else like FormArray or FormGroup or your own custom class extending AbstractControl. The best Angular can do is tell you that's either some sort of AbstractControl, or that it's maybe null if you'd removed it in the meantime.

From the code your posted, it doesn't look like you're changing or removing userName in the signupForm, so a better solution is probably to do and explicit cast:

get username () {
  return this.singupForm.get('userName') as FormControl
}

This tells TypeScript:

Look, I know what I'm doing. Yes, get could return null, but I know that it won't, for my case. So please treat this value as if its type were FormControl.

Now, in your template (and everywhere else), you can simply use {{ username.valid }}, as you originally intended.

Upvotes: 5

NaingMinZaw
NaingMinZaw

Reputation: 101

Finally, I got this error, you can use '?' to solve this problem see the following code. Eg;

 *ngIf="username?.invalid"

Upvotes: 2

Related Questions