我有一个表包含多行,每行都有一个添加按钮。当我单击添加按钮时,应该在该行的下方创建一个与该行相似的新行。这是下面的代码
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
ngOnInit() {
}
groups=[
{
"name": "pencils",
"items": "red pencil"
},
{
"name": "rubbers",
"items": "big rubber"
},
];
//console.log(this.groups);
}
<div class="container">
<h2>Basic Table</h2>
<p>The .table class adds basic styling (light padding and only horizontal dividers) to a table:</p>
<table class="table border">
<tbody>
<tr *ngFor="let row of groups">
<td> {{row.name}} </td>
<td> {{row.items}} </td>
<td> <button>Add</button> </td>
</tr>
</tbody>
</table>
</div>
答案 0 :(得分:1)
只需将其添加到数组中,视图就会更新。
<td> <button (click)="addItem()">Add</button> </td>
public addItem(): void {
this.groups.push({name: 'foo', items: 'bar});
}
答案 1 :(得分:0)
a。将点击处理程序添加到按钮
<button (click)="addRow(row)">Add</button>
b。向组件添加方法
addRow(row: {name: string; items: string;}): void {
this.groups.push(row);
},
答案 2 :(得分:0)
当我单击“添加”按钮时,应在该行下方创建一个新行 与该行相似的行。
将当前索引传递到单击按钮的位置,然后在该索引处插入一个项目。
HTML:
<tr *ngFor="let row of groups; let i = index">
<td> {{row.name}} </td>
<td> {{row.items}} </td>
<td> <button (click)="addItem(i)">Add</button> </td>
</tr>
组件:
我们正在使用JavaScript的splice()方法在该特定索引处插入项目。
addItem(index) {
var currentElement = this.groups[index];
this.groups.splice(index, 0, currentElement);
}
StackBlitz上的实时演示:https://stackblitz.com/edit/angular-1pd6yx