20

I would like to know how to make a checkbox checked if the value is true, and unchecked if false with Angular2.

Adult <input type="checkbox" value="{{person.is_adult}}">

{{person.is_adult}} is a boolean

Can someone please suggest anything? Thanks

3 Answers 3

30

{{}} does string interpolation and stringifies true and false and Angular by default uses property binding and I assume the property expects boolean values not strings:

<input type="checkbox" [checked]="person.is_adult">

This might work as well

<input type="checkbox" attr.checked="{{person.is_adult}}">

because with attribute binding the browser might translate it from the attribute (which can only be strings) to boolean when reading it into its property.

It is also checked instead of value

You can also use ngModel

<input type="checkbox" [ngModel]"person.is_adult" name="isAdult">
<input type="checkbox" [(ngModel)]"person.is_adult" name="isAdult">

for one-way or two-way binding.
Ensure your have the FormsModule imported if you use ngModel.

Sign up to request clarification or add additional context in comments.

2 Comments

Using value did not work for me only checked worked.
Right, I didn't pay attention to the attribute name (copied from the question) but only to the mistake in the binding.
15

you are missing square bracket around checked

<input type="checkbox" [checked]="person.is_adult">

Hope this helps!!

Comments

0

Try the following :

<input type="checkbox" [checked]="person.is_adult">

If you are using ngModel :

When ngModel is used in a form it won't work. However, you should use [ngModelOptions] attribute like

<input
  type="checkbox"
  name="is_adult"
  [(ngModel)]="person.is_adult"
  [ngModelOptions]="{standalone: true}"/> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.