【发布时间】: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