Search code examples
angularcheckboxlistngmodel

Check checkbox in CheckBoxList based on an object property


I need to check a checkbox in the list of checkboxes. This code is creating checkboxes:

<div *ngFor="let course of user?.CurrentClasses">
    <input type="checkbox" [(ngModel)]="course.ClassId" [ngModelOptions]="{standalone: true}" (change)="onCheckboxChange($event)" />
    {{ course.CourseCode }}-{{ course.TermCode }}-{{ course.CourseSection }}
</div>

I am not sure if I should be using ngModel and ngModelOptions. I just am not sure how to implement. Basically, in typescript I have a classId value. In the template, one of the courses (course.ClassId property) in user.CurrentClasses array will equal the classId value available in the compoment/ts file. I need to check the checkbox of the matching one. I just am not sure how to accomplish this. course in CurrentClasses array does not have a property indicating whether it should be checked. It needs to be checked based on the classId value matching.


Solution

  • The ngModel is used to link an input to a value, this is not necessary for a checkbox unless you are storing the state.

    To simply have the checkbox with the corresponding classId checked, you will want to add [checked]="conditon" into the element, i.e:

    <input type="checkbox" [checked]="course.ClassId == classId"