亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 130 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號