Angular 2-内联编辑表行,然后保存新数据 [英] Angular 2 - Edit table rows inline, then save the new data
问题描述
我正在尝试制作一个组件,以TableData模型中的行形式显示数据,
I am trying to make a component that shows data in rows from TableData model,
export class TableData{
constructor(
public id: number,
public country: string,
public capital: string){ }
}
我的数据在这样的组件中
I have my data in the component like this,
tableData: TableData[] = [
new TableData(1, 'Canada','Ottawa'),
new TableData(2, 'USA','Washington DC'),
new TableData(3, 'Australia','Canberra'),
new TableData(4, 'UK','London')
];
然后在我的组件中,我正在创建一个像这样的表,
Then in my component, I am creating a table like this,
<table>
<tbody>
<tr *ngFor="#row of tableData>
<td contenteditable='true'>{{ row.id }}</td>
<td contenteditable='true' (click)="onRowClick($event)">{{ row.country }}</td>
<td contenteditable='true'>{{ row.capital }}</td>
</tr>
</tbody>
<span>{{ tableData | json }}</span>
</table>
onRowClick(event){
console.log(event);
}
当我将<td>
元素标记为"contenteditable"时,我能够编辑数据,但是不知道如何保存或检索更新的值.我检查了传递给onRowClick方法的事件"数据,但无法检索行的"id"(它为空.event.srcElement.id或event.target.id均为空).
I am able to edit the data as I marked the <td>
element as 'contenteditable', but don't know how to save it or retrieve the updated values. I inspected 'event' data that's passed to onRowClick method, but couldn't retrieve the 'id' of row (it's empty. event.srcElement.id or event.target.id are both empty).
简而言之,我想编辑表并查看它是否更新了tableData变量.抱歉,第一次没有明确要求.
In short, I want to edit the table and see it update the tableData variable. Sorry for not asking it clearly the first time.
非常感谢您提供有关如何解决我的问题的指导!
Any guidance on how to solve my problem is greatly appreciated!
推荐答案
提示将id
作为标志以及您的id传递,然后根据在表行上单击的id进行检测,这是示例-
Juts pass id
as flag along with your id then detect as per id clicked on the row of table here is example -
tableData: TableData[] = [
new TableData('Canada','Ottawa',1),
new TableData('USA','Washington DC',2),
new TableData('Australia','Canberra',3),
new TableData('UK','London',4)
];
-
PS-您的代码在此处抛出错误,请在此处更正.
PS - your code is throwing error here please correct here.
<tr *ngFor="#row of tableData>
应使用
<tr *ngFor="#row of tableData">
在这里工作演示 柱塞示例
working demo here Plunker example
更新- 尝试在
td
上使用(input)
事件绑定,并使用event.target.outerText
获取更新的文本.请检查更新plnukr.Update - Try using
(input)
event binding on thetd
and get the updated text usingevent.target.outerText
. please check update plnukr.<tr *ngFor="#row of tableData"> <td contenteditable='true' (input)="onRowClick($event, row.id)">{{ row.country }}</td> <td contenteditable='true'>{{ row.capital }}</td> </tr> onRowClick(event, id){ console.log(event.target.outerText, id); }
这篇关于Angular 2-内联编辑表行,然后保存新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!