【问题标题】:Cannot create property 'selected' on string, using ngModel with Angular无法在字符串上创建属性“选定”,使用 ngModel 和 Angular
【发布时间】:2020-08-04 04:48:23
【问题描述】:

所以我尝试像这样使用[(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>

我的accounts被创建并填写在组件中: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。如果有人能帮助理解这里的问题会很高兴?

【问题讨论】:

  • 这里的名字是string。它不包含属性selected。如果它是一个对象,那么您可以定义一个属性selected
  • 是的,我从另一个线程中理解了这一点,但我该如何让它发挥作用?
  • 哦,我刚刚从ngModel 中删除了.name,现在它是对象,明白了,非常感谢!
  • 复选框将为绑定的任何内容分配一个布尔值。所以现在你的Account 实例上会有一个布尔属性。由于 selected 最初是未定义的,因此该复选框最初不会被选中。
  • 您需要将类型从字符串更改为对象并为此声明所需的属性。

标签: html angular angular-ngmodel


【解决方案1】:

您的数组中似乎需要有 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);

【讨论】:

  • 如果我只是将它用作像[(ngModel)]="this.account.selected" 这样的对象呢?它似乎正在工作。但是如何访问选定的值?比如我想console.log()组件中选中的元素?
  • 好的,知道了,但不应该有[(ngModel)]="this.account.selected"吗? name 字段已过时,不是吗?
  • @developer1 哎呀,我很着急,请看我更新的答案
  • 好的,现在为什么要删除this
  • @developer1 因为this is not necessary in template
猜你喜欢
  • 1970-01-01
  • 2018-12-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
相关资源
最近更新 更多