0
我有一個使用* ngFor指令填充的表。用戶可以點擊表格中的每個單元格,並通過'contentEditable'屬性編輯它的值。當前實現更新表中的數據,但不更新組件中的數據。當用戶使用原生2角度的工具更改單元格中的數據時,是否可以更新組件中的數據?如果是這樣,怎麼樣?如何實現html表和angular 2組件之間的2路數據綁定
這是HTML文件:
<table id="data-table" class="table table-striped">
<thead>
<tr>
<th *ngFor="let round of rounds">{{ round.title }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let player of players">
<td contenteditable="true">{{ player.name }}</td>
<td contenteditable="true">{{ player.round1 }}</td>
<td contenteditable="true">{{ player.round2 }}</td>
<td contenteditable="true">{{ player.round3 }}</td>
</tr>
</tbody>
</table>
這是組件:
import { Component, OnInit } from '@angular/core';
import { BooksAndRunService } from '../books_and_run.service';
@Component({
moduleId: module.id,
selector: 'books-and-run-play',
templateUrl: './books_and_run_play.component.html',
styleUrls: ['./books_and_run_play.component.css'],
})
export class BooksAndRunPlayComponent implements OnInit {
constructor(private booksAndRunService: BooksAndRunService) { }
currentRound = 1;
rounds = [
{title: ""},
{title: "Round 1"},
{title: "Round 2"},
{title: "Round 3"},
{title: "Round 4"},
{title: "Round 5"},
{title: "Round 6"},
{title: "Round 7"},
]
players = [
{
name: "Bob",
round1: 0,
round2: 0,
round3: 0,
round4: 0,
round5: 0,
round6: 0,
round7: 0,
},
{
name: "Joe",
round1: 0,
round2: 0,
round3: 0,
round4: 0,
round5: 0,
round6: 0,
round7: 0,
},
{
name: "Jim",
round1: 0,
round2: 0,
round3: 0,
round4: 0,
round5: 0,
round6: 0,
round7: 0,
},
{
name: "Sarah",
round1: 0,
round2: 0,
round3: 0,
round4: 0,
round5: 0,
round6: 0,
round7: 0,
},
{
name: "Jane",
round1: 0,
round2: 0,
round3: 0,
round4: 0,
round5: 0,
round6: 0,
round7: 0,
},
{
name: "Jill",
round1: 0,
round2: 0,
round3: 0,
round4: 0,
round5: 0,
round6: 0,
round7: 0,
},
];
ngOnInit(): void {
// this.players = this.booksAndRunService.getPlayers();
}
}
真棒這個作品,謝謝!只是好奇,這是否在表中的每個單元格上創建一個事件監聽器? – FlashBanistan
是的,如果您想要使用2路數據綁定,您必須爲使用contenteditable =「true」的每個元素執行此操作。所以是的,當ngFor完成後,你將最終得到每個元素的事件監聽器,但這應該不成問題。只要小心一點,不要誤認爲你正在調用的對象的屬性,這就是全部:) – Lys