Angular reactive forms checkbox validations

Published

I’m trying to make a required validation to my checkboxes.

My TS file :

public colors: Array<any> = [
     { description: 'White', value: 'White' },
     { description: 'Black', value: 'Black' },
     { description: 'Blue', value: 'Blue' },
     { description: 'Green', value: 'Green' },
     { description: 'Yellow', value: 'Yellow' },
     { description: 'Red', value: 'Red' },
];
    
constructor(
    private formBuilder: FormBuilder,
    private heroService: HeroService,
    private toastr: ToastrService
  ) {
  this.fromInit();
}

ngOnInit(): void {}

fromInit() {
  this.heroCreateForm = this.formBuilder.group({
    suitColors: new FormArray([], [Validators.required]),
  });
}

onCheckChange(event) {
  const formArray: FormArray = this.heroCreateForm.get(
    'suitColors'
  ) as FormArray;

  if (event.target.checked) {
    formArray.push(new FormControl(event.target.value));
  } else {
    let i: number = 0;

    formArray.controls.forEach((ctrl: FormControl) => {
      if (ctrl.value == event.target.value) {
        formArray.removeAt(i);
        return;
      }
      i++;
    });
  }
}


invalidSuitColorsMessage() {
   // this function doesn't work
   if (this.suitColors.errors?.required)
      return "You must choose the hero's suit colors";
}

My HTML file :

<div class="main-content">
  <form [formGroup]="heroCreateForm" (ngSubmit)="createHero()">
    <div class="container">

      <div class="input-container-suitColors-input">
        <label><b>Suit colors: </b></label>
        <ng-container *ngFor="let color of colors; let i=index">
          <div class="radio-contatiner">
            <input type="checkbox"
                   [value]="color.value"
                   (change)="onCheckChange($event)">
            {{color.description}}
          </div>
        </ng-container>
      </div>

      <div class="invalid-input-message"
           *ngIf="suitColors.touched && suitColors.invalid">{{invalidSuitColorsMessage()}}</div>

// here is the issue. I'm getting here an error

      <hr>

      <button type="submit"
              class="registerbtn"
              [disabled]="heroCreateForm.invalid">Register</button>
    </div>
  </form>
</div>

Error

Cannot read properties of undefined (reading ‘touched’)

I do understand why it does work. I search online and didn’t find any solution to my issue.

I’m trying to show a message if the required error happens on those checkboxes

Does anyone can take a look and explain to me why does it happen and how should I fix it?

Source: Angular Questions

Published
Categorized as angular, angular-reactive-forms Tagged ,

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq