Skip to content

Enforce Check Box Required (Simple Form Validation)

Tyler Ruff edited this page Jul 1, 2022 · 2 revisions

To use a checkbox to control whether or not a form can be submitted, observe the following example:

  1. First, start by setting a variable (isChecked) in your component.ts file:
...
export class ExampleComponent implements OnInit {
	isChecked: boolean = false;

	// The fieldsChange function is invoked when the check
	// box is changed (onChange)
	public fieldsChange(values: any): void{
		this.isChecked = values.currentTarget.checked;
	}

	ngOnInit(): void { }
}
  1. Then, add the following HTML to your component.html file to "switch" the isChecked condition:
...
<input id="agree" type="checkbox" name="agree" value="1" required (change)="fieldsChange($event)">
...
<ng-container *ngIf="isChecked; then submitButton; else disabledButton"></ng-container>
<ng-template #disabledButton>
	<button type="button" disabled>
		Register
	</button>
</ng-template>
<ng-template #submitButton>
	<button type="submit">
		Register
	</button>
</ng-template>
...

Sources

Index w/ for loop

<ul>
    <li *ngFor="let item of items; let i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>

Sources