Suppose you want to set the state of a checkbox based on a condition in angular.
State means making it checked/unchecked or select/unselect it.

A common scenario would be to display a checkbox checked or unchecked based on its last saved state in page edit mode.

Checked property

A checkbox in HTML has a checked property which makes a checkbox checked or unchecked.
There are two ways to use this property to make a checkbox checked as shown below.

<!-- Add checked property -->
<input type="checkbox" checked/>

<!-- Set checked property to true to check  -->
<input type="checkbox" checked="true"/>

<!-- Set checked property to false to uncheck -->
<input type="checkbox" checked="false"/>

If checked property is present or true, the checkbox is checked.
If checked property is not present or false, the checkbox is unchecked.

Conditionally check checkbox angular

Using the value assigned to the checked property of a checkbox, we can display it as checked or unchecked in angular.
In angular, checked property of a checkbox is defined between square brackets as [checked] since it is an input property of checkbox.

Simply assign [checked] property to an expression. This expression might be a condition or expression or a variable(property) defined in typescript class.
In any case, the condition should evaluate to true or false.
If it is true, the checkbox will be checked else not.
Example,

HTML template for example is given below.

<!-- Set checked property based on expression  -->
<input type="checkbox" [checked]="checkMe == 'Y'"/>

<!-- Set checked property to false to uncheck -->
<input type="checkbox" [checked]="isChecked"/>

In the first checkbox, [checked] property is evaluated on the basis of an expression comparing the value of checkMe variable with Y.
If the value of variable will be Y, the expression will be true, hence the checkbox will be checked.

Second checkbox sets the value of [checked] property as the value of isChecked property defined in typescript or component class.
This is called property binding in angular.

Typescript or Component class for this template is given below.

export class CheckboxComponent {
   checkMe = "N";

   isChecked = true;
}

As per the above typescript definition, first checkbox which compares the value of checkMe variable with Y will not be checked since the comparison checkMe == 'Y' will be false.
Second checkbox should be checked since the expression [checked]="isChecked" will evaluate to [checked]="true".


This way, you can easily set the state of checkbox to checked or unchecked based on a condition in angular.

Leave a Reply