所以我嘗試[(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);
- 1 回答
- 0 關注
- 130 瀏覽
添加回答
舉報
0/150
提交
取消