Published: July 12 2020

Angular + Reactive Forms - Required Checkbox Example

Example built with Angular 10.0.3 and Reactive Forms

Other versions available:

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()".

<div class="card m-3">
    <h5 class="card-header">Angular + Reactive Forms - Required Checkbox</h5>
    <div class="card-body">
        <form [formGroup]="form" (ngSubmit)="onSubmit()">
            <div class="form-group form-check">
                <input type="checkbox" formControlName="acceptTerms" id="acceptTerms" class="form-check-input" [ngClass]="{ 'is-invalid': submitted && f.acceptTerms.errors }" />
                <label for="acceptTerms" class="form-check-label">Accept Terms & Conditions</label>
                <div *ngIf="submitted && f.acceptTerms.errors" class="invalid-feedback">Accept Ts & Cs is required</div>
            </div>
            <div>
                <button class="btn btn-primary mr-1">Submit</button>
                <button class="btn btn-secondary" type="reset" (click)="onReset()">Reset</button>
            </div>
        </form>
    </div>
</div>

 


Need Some Angular Help?

Search fiverr for freelance Angular developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by