This is a quick example of how to implement a required checkbox field in Angular with Reactive Forms. For a more detailed registration form example that includes a bunch of other fields see Angular 10 - Reactive Forms Validation Example.

Here it is in action:

(See on StackBlitz at https://stackblitz.com/edit/angular-reactive-forms-required-checkbox)

Angular Required Checkbox App Component

The app component contains an example form (FormGroup) which contains a single boolean field with a requiredTrue validator to make a checkbox field required. The app component uses a FormBuilder to create an instance of a FormGroup that is stored in the form property. The form property is then bound to the <form> element of the app template below using the [formGroup] directive.

The component contains a convenience getter property f to make it easier to access form controls from the template. So for example you can access the confirmPassword field in the template using f.confirmPassword instead of registerForm.controls.confirmPassword.

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

@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent implements OnInit {
    form: FormGroup;
    submitted = false;

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.form = this.formBuilder.group({
            acceptTerms: [false, Validators.requiredTrue]
        });
    }

    // convenience getter for easy access to form fields
    get f() { return this.form.controls; }

    onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.form.invalid) {
            return;
        }

        // display form values on success
        alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.form.value, null, 4));
    }

    onReset() {
        this.submitted = false;
        this.form.reset();
    }
}

App Component Template

The app component template contains the html markup for displaying the example required checkbox form in the browser. The form element uses the [formGroup] directive to bind to the form FormGroup in the app component above.

The form binds the form submit event to the onSubmit() handler in the app component using the Angular event binding (ngSubmit)="onSubmit()". Validation messages are displayed only after the user attempts to submit the form for the first time, this is controlled with the submitted property of the app component.

The reset button click event is bound to the onReset() handler in the app component using the Angular event binding (click)="onReset()".

#angular #reactive forms #required checkbox #component #formgroup

Angular + Reactive Forms - Required Checkbox Example
22.00 GEEK