angularangular-ngmodel

How to use *ngFor to create repeating checkbox input fields in Angular


I am trying to create multiple checkbox fields using ngFor. I have an array which consists of project ids, names and types. So, now I am trying to create multiple input checkbox fields according to the number of projects that I have.

The ng-serve works fine and shows no error but the browser shows the error on [(ngModel)] at the frontend.

The code that I have been trying with is below: Here is the definition of projectsList array:

    let loggedData = JSON.parse(localStorage.getItem('loggedInfo'));
        this.commonService.getProjectList(loggedData.value).then((response)=>{
            this.allProjectList = response;
            console.log('this.allProjectList',response);
            var checkedItems = [];
            for (var i = 0; i < Object.keys(response).length; i++) {
              this.projectsList.push({id: response[i].id, projectName: response[i].projectName, projectNumber: response[i].projectNumber})
            }
        });

And here is the template part in html:

    <tr *ngFor="let cl of projectsList; let i = index" [attr.data-index]="i"><td>
                                     <div style="width:150"><font style="font-size: 8pt;">{{cl.projectName}} - {{cl.projectNumber}}</font></div>
                                  </td>
                                  <td>
                                     <input class="form-check-input " type="checkbox" value="false" name="cl.projectNumber" [(ngModel)]="accountLoginPrivilegeModel.activeSubaccountView[cl.projectNumber]">
                                  </td>
                                  <td>
                                     <input class="form-check-input " type="checkbox" name="cl.projectNumber" [(ngModel)]="accountLoginPrivilegeModel.activeSubaccountTransfer[cl.projectNumber]">
                                  </td>
                               </tr>

And here is the error that I am getting at [(ngModel)]. enter image description here

Any help would be more than appreciable.


Solution

  • Here is a small stackblitz example of what you are trying to do, but with dummy data.

    stackblitz