rachida marzouk
rachida marzouk

Reputation: 17

object is possibly 'null' REACTIVE FORM angular 11

i want to apply reactive form validation system, and display error messages according to error, but it gives me error: object is possibly 'null'.

signup.component.html

<form [formGroup]="form">
        <div class="form-group">
            <label for="username">Username</label>
            <input 
            formControlName="username"
            class="form-control"
            id="username"
            type="text">
        <div class="alert alert-danger" *ngIf="username?.touched && username?.invalid">
                <div *ngIf="username.errors.required">username is required !</div>
                <div *ngIf="this.form.controls['username'].errors?.minlength">username must have at least {{ username.errors.minlength.requiredLength }} characters</div>
        </div>
        </div>
</form>

signup.component.ts

form = new FormGroup({
    username: new FormControl('',[
      Validators.required,
      Validators.minLength(3),
    ]),
    
  })

  get username(){
    return this.form.get('username')
  }

Upvotes: 0

Views: 529

Answers (1)

Rachid O
Rachid O

Reputation: 14002

I suspect this line should have a ?

<div *ngIf="username?.errors?.required">username is required !</div>

Upvotes: 2

Related Questions