1

I am using the Reactive form Validation code but I got an error. Here is my code. Did I miss something?

I am using Form Builder to perform the validation operation in Angular.

src/app/mValidation.component.html:5:42 - error TS2531: Object is possibly 'null'.
<form [formGroup]="userForm" (ngSubmit)="saveData(userForm)">
    <div>
        Name:<input type="text" formControlName="Name"/>
        <div *ngIf="userForm.get('Name').errors" class="text-danger"></div>
    </div>
    <div>
        userName:<input type="text" formControlName="userName" class="text-danger"/>
    </div>
    <div>
        Email:<input type="text" formControlName="Email" />
    </div>
    <div>
        <input type="submit" value="SAVE">
    </div>
</form>

My Ts Page code

userForm:FormGroup;
  constructor(public fb:FormBuilder) {
    this.userForm=this.fb.group({
      Name : ['',Validators.required],
      userName : ['',[Validators.required,Validators.minLength(4)]],
      Email : ['',[Validators.required,Validators.email]]
    })
   }
1
  • You are getting an error because of the strictTemplate feature of Angular. It says userForm.get('Name') can be null. To solve the issue, you can use Non-Null Assertion Operator like userForm.get('Name')!. errors. Or you can use a generic and pretty cool solution with using @ngx-validate/core Commented Jun 17, 2021 at 9:12

1 Answer 1

4

You have to add ? to userForm.get.

userForm.get('Name')?.errors
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.