要在不刷新表格的情况下添加新行,可以使用Angular Material表格和数据源进行操作。以下是一个示例代码解决方法:
首先,确保已经安装了Angular Material和相关的依赖库。
在你的组件中,导入所需的库和模块:
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { MatPaginator } from '@angular/material/paginator';
@Component({
selector: 'app-my-table',
templateUrl: './my-table.component.html',
styleUrls: ['./my-table.component.css']
})
export class MyTableComponent implements OnInit {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource: MatTableDataSource;
newData: any = {};
// 获取表格的排序和分页组件
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
ngOnInit() {
// 初始化表格数据源
this.dataSource = new MatTableDataSource();
this.dataSource.data = [
{position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
{position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
{position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
{position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
];
// 设置排序和分页
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
}
// 添加新行
addNewRow() {
const data = this.dataSource.data;
data.push(this.newData);
this.dataSource.data = data;
this.newData = {};
}
}
No.
{{element.position}}
Name
{{element.name}}
Weight
{{element.weight}}
Symbol
{{element.symbol}}
相关内容