-
-
Notifications
You must be signed in to change notification settings - Fork 0
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:
- 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 { }
}
- 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>
...
<ul>
<li *ngFor="let item of items; let i = index" [attr.data-index]="i">
{{item}}
</li>
</ul>
Join the Blazed Development Group today to get involved in open source collaborative projects.
Discover our FREE learning resources, the Blazed University, Web Development School, and Blazed City.