In this video we will discuss
1 Working with a checkbox control in Angular Template Driven forms
2. How to have a checkbox checked by default
3. How to disable a checkbox
Working with a checkbox in Angular is very similar to working with a radio button. We want to include "Is Active" checkbox in the Create Employee form as shown below. When we check the checkbox, "isActive" property should reflect in the Angular generated for model. Also, when we click the "Save" button we want the "isActive" property value to be logged to the console.
To achieve this all you have to do is include the following HTML in create-employee.component.html file.
Please replace [ with LESSTHAN symbol and ] with GREATERTHAN symbol
[input type="checkbox" name="isActive" [(ngModel)]="isActive"]Is Active
If we include "checked" attribute on a checkbox, we expect checkbox to be checked by default when the form initially loads. But you will discover that is not the case.
[input type="checkbox" name="isActive" [(ngModel)]="isActive" checked]Is Active
However, if you remove the "ngModel" directive from the checbox, then it gets checked as expected. Notice the "ngModel" directive is removed from the checkbox.
[input type="checkbox" name="isActive" checked]Is Active
With Angular Template Driven forms, we use "ngModel" directive for two-way data binding. So the moment we put it back in place the "checked" attribute does not work. To make it work include "isActive" property in the component class and initialise it to true.
isActive = true;
At this point you will have "IsActive" checkbox checked by default when the form loads. Now, even if we remove the "checked" attribute from the checkbox it is still checked by default when the form loads. This is because of the two-way data binding that we get with "ngModel" directive. For our form we do not want the checkbox to be checked by default, so remove the "checked" attribute and the "isActive" property from the component class.
How to disable a checkbox : To disable a checkbox, use the disabled attribute
[input type="checkbox" name="isActive" [(ngModel)]="isActive" disabled]Is Active
Another important point to keep in mind. By default, disabled form controls are not included in the Angular auto generated form model. Since, the "Is Active" checkbox is disabled, it will not be included in the Angular generated form model.
In our form, we do not want the checkbox to be disabled, so please remove the disabled attribute.
Text version of the video
Angular CRUD Tutorial
Angular CRUD Tutorial Text Articles & Slides
All Dot Net and SQL Server Tutorials in English
All Dot Net and SQL Server Tutorials in Arabic