Suppose you want to set the state of a checkbox based on a condition in angular. A common scenario would be to show a checkbox checked or unchecked based on its last saved stated.

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 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 variable defined in typescript or component class.

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. Do not forget to click the clap if the article helped.

2

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.