Search code examples
angularcheckboxangular8checked

Default checked checkbox not working in angular


I tried almost all ways checked,checked="true",[checked]="true" and tried different answers like this one on stackoverflow but not working for me

    <ng-template #content>

    <label class="switch">
        <input  type="checkbox" name="{{day.id}}"  ngModel required #{{day.id}}="ngModel"  [checked]="true"  checked="true">
        <span class="slider round"></span>
    </label>
</ng-template>

<ng-template #other_content>

    <label class="switch">
        <input type="checkbox" name="{{day.id}}" ngModel required #{{day.id}}="ngModel">
        <span class="slider round"></span>
    </label>
</ng-template>

Solution

  • You are registering form control together with ngModel and name attribute. How to mark ngModel for template driven forms, it can vary from ngModel, [ngModel] or [(ngModel)]. Your pick for what solution you need. Here you have marked with ngModel means that the form control has no value. Angular forms do not care about the checked attribute, but listens to what value the form control has!

    You can overcome this by instead of using ngModel, use [ngModel] and capture a true value for that field, so for that field change:

    <input type="checkbox" name="{{day.id}}" required #{{day.id}}="ngModel" [ngModel]="true">