所以我嘗試[(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已創(chuàng)建并填充組件:accounts: Account[] = [];我的Account對(duì)象:export class Account {name: string;surname: string;}我越來越ERROR TypeError: Cannot create property 'selected' on string 'John'我看到了這個(gè)帖子:Cannot create property 'selected' on string 'Information Technology' angularjs但不太明白如何將提到的修復(fù)應(yīng)用于我的案例,也許是因?yàn)槲沂褂玫氖?Angular 而不是 AngularJS。如果有人能幫助理解這里的問題,我會(huì)很高興嗎?
1 回答

至尊寶的傳說
TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
看來您需要selected在數(shù)組中擁有屬性。因此,為了避免污染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 關(guān)注
- 126 瀏覽
添加回答
舉報(bào)
0/150
提交
取消