Checkbox checked if boolean is true with Angular2

前端 未结 3 1016
灰色年华
灰色年华 2021-01-03 22:19

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

Adult 

        
相关标签:
3条回答
  • 2021-01-03 22:41

    {{}} 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.

    0 讨论(0)
  • 2021-01-03 22:51

    you are missing square bracket around checked

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

    Hope this helps!!

    0 讨论(0)
  • 2021-01-03 22:59

    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}"/> 
    
    0 讨论(0)
提交回复
热议问题