为了账号安全,请及时绑定邮箱和手机立即绑定

使用 ngModel 和 Angular 无法在字符串上创建属性“selected”

使用 ngModel 和 Angular 无法在字符串上创建属性“selected”

芜湖不芜 2024-01-22 17:08:53
所以我尝试[(ngModel)]这样使用:  <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>Myaccounts已创建并填充组件:accounts: Account[] = [];我的Account对象:export class Account {name: string;surname: string;}我越来越ERROR TypeError: Cannot create property 'selected' on string 'John'我看到了这个帖子:Cannot create property 'selected' on string 'Information Technology' angularjs但不太明白如何将提到的修复应用于我的案例,也许是因为我使用的是 Angular 而不是 AngularJS。如果有人能帮助理解这里的问题,我会很高兴吗?
查看完整描述

1 回答

?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

看来您需要selected在数组中拥有属性。因此,为了避免污染Account类,您可以使用map方法:


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

和 HTML:


<tr *ngFor="let account of withSelectedProperty">

  <td>

      <input type="checkbox" [(ngModel)]="account.selected" name="account">

          {{account.name}}

  </td>

</tr>

更新:


您可以使用方法filter来获取所有选定的值:


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


查看完整回答
反对 回复 2024-01-22
  • 1 回答
  • 0 关注
  • 23 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信