Multi-Checkbox Validation In Angular 13

Example of an Angular 13 multi-checkbox
  • Establishing an Angular Form
  • Making a Checkbox
  • Multiple Checkboxes are Handled
  • Checkbox Validation in Angular
FormGroup:

creates a form object with attributes for FormControl and FormArray in Reactive Forms.

FormArray:

The FormControl is stored in an array form by FormArray, which is identical to FormGroup.

FormControl:

It alludes to a particular input field established inside the FormGroup that holds the value supplied by the user.

Validators:

It provides a collection of pre-defined validators that may be utilised by form controls to validate an Angular form.

Angular Checkbox Validation

Using the Validators Angular Form service, we will validate the Angular Checkbox in this phase. We can validate this easily. In the beginning, we will display an error message to the users and instruct them to select at least one checkbox from the list of checkboxes.

In the file app.module.ts, update the code.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CheckboxComponent } from './checkbox/checkbox.component';

@NgModule({
  declarations: [
    AppComponent,
    CheckboxComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In the file app.component.ts, update the code.

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

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

  form: FormGroup;
  items: Array<any> = [
    { name: 'Lexus', value: 'Lexus' },
    { name: 'Porsche', value: 'Porsche' },
    { name: 'Bugatti', value: 'Bugatti' },
    { name: 'Rolls Royce', value: 'Rolls Royce' },
    { name: 'BMW', value: 'BMW' },
  ];
  constructor(private formBuilder: FormBuilder) {
    this.form = this.formBuilder.group({
      checkArray: this.formBuilder.array([], [Validators.required]),
    });
  }
  ngOnInit(): void {
  }
  onCheckboxChangeValue(data: any) {
    const checkArray: FormArray = this.form.get('checkArray') as FormArray;
    if (data.target.checked) {
      checkArray.push(new FormControl(data.target.value));
    } else {
      let i: number = 0;
      checkArray.controls.forEach((item: any) => {
        if (item.value == data.target.value) {
          checkArray.removeAt(i);
          return;
        }
        i++;
      });
    }
  }
  submitForm() {
    console.log(this.form.value);
  }
}

In the file app.component.html, update the code.

<section class="main">
  <form [formGroup]="form" (ngSubmit)="submitForm()" novalidate>
    <div *ngFor="let item of items; let i=index">
      <label>
        <input type="checkbox" [value]="item.value" (change)="onCheckboxChangeValue($event)" />
        {{item.name}}
      </label>
    </div>
   <div class="mb-3 mt-3">
    <span class="checkbox_error" *ngIf="this.form.controls['checkArray'].errors?.['required']">
        Checkbox must have at least one value selected.
    </span>
   </div>
    <button type="submit">Submit</button>
  </form>
</section>
Run Application

Conclusion

The Angular Checkbox lesson is now complete. We learnt how to construct multiple checkboxes, pick and deselect multiple checkboxes, and set the checkbox values in the reactive form in this lesson.

The required validation for numerous checkboxes was also examined.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories