Search code examples
htmlangularangular-ngmodel

Cannot create property 'selected' on string, using ngModel with Angular


so I'm trying to use [(ngModel)] like this:

  <div class="items">
    <tbody>
    <tr *ngFor="let account of this.accounts">
      <td>
          <input type="checkbox" [(ngModel)]="this.account.name.selected" name="account">
              {{account.name}}
      </td>
    </tr>
    </tbody>
  </div>

My accounts is created and filled in the component: accounts: Account[] = [];

My Account object:

export class Account {
name: string;
surname: string;
}

I'm getting ERROR TypeError: Cannot create property 'selected' on string 'John'

I saw this thread: Cannot create property 'selected' on string 'Information Technology' angularjs But didn't quite understand how to apply mentioned fix to my case, maybe because I'm using Angular and not AngularJS. Would be glad if anyone could help a bit understanding the problem here?


Solution

  • It looks like you need to have selected property in your array. So to avoid polluting Account class, you can use map method:

    let withSelectedProperty = this.accounts.map(s=> ({...s, selected: false}));
    

    And HTML:

    <tr *ngFor="let account of withSelectedProperty">
      <td>
          <input type="checkbox" [(ngModel)]="account.selected" name="account">
              {{account.name}}
      </td>
    </tr>
    

    UPDATE:

    You can use method filter to get all selected values:

    let onlySelected = this.withSelectedProperty.filter(f => f.selected);