这是一个使用Angular来编辑行并将值存储在数组中的示例代码:
在component.ts文件中:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// 定义一个数组来存储行的值
rows: any[] = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 35 }
];
// 定义一个变量来追踪当前编辑的行
editedRow: any = {};
// 编辑行
editRow(row: any) {
this.editedRow = { ...row };
}
// 保存行
saveRow(row: any) {
// 将编辑后的值保存到数组中
const index = this.rows.indexOf(row);
this.rows[index] = { ...this.editedRow };
// 清空当前编辑的行
this.editedRow = {};
}
}
在component.html文件中:
{{ row.name }}
{{ row.age }}
这个示例中,使用*ngFor
指令遍历数组中的每一行,并根据editedRow
变量来判断是否处于编辑状态。当点击“编辑”按钮时,会调用editRow
方法将当前行的值保存到editedRow
变量中,并显示可编辑的输入框。当点击“保存”按钮时,会调用saveRow
方法将编辑后的值保存到数组中,并清空editedRow
变量。
希望这个示例能够帮助到你!
上一篇:Angular编辑文本的多种方法
下一篇:Angular变量