要创建一个响应式表格,您需要使用Angular Material的表格组件和Flex布局。以下是一个示例解决方案:
npm install @angular/material @angular/cdk @angular/flex-layout
app.module.ts
文件中添加以下代码:import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSortModule } from '@angular/material/sort';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
FlexLayoutModule,
MatTableModule,
MatPaginatorModule,
MatSortModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
文件中添加以下代码:import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
export interface UserData {
id: string;
name: string;
email: string;
phone: string;
}
const ELEMENT_DATA: UserData[] = [
{ id: '1', name: 'John Doe', email: 'john.doe@example.com', phone: '1234567890' },
{ id: '2', name: 'Jane Smith', email: 'jane.smith@example.com', phone: '9876543210' },
{ id: '3', name: 'Robert Johnson', email: 'robert.johnson@example.com', phone: '5555555555' },
{ id: '4', name: 'Lisa Brown', email: 'lisa.brown@example.com', phone: '1111111111' },
{ id: '5', name: 'Michael Davis', email: 'michael.davis@example.com', phone: '9999999999' }
];
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
displayedColumns: string[] = ['id', 'name', 'email', 'phone'];
dataSource: MatTableDataSource;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
this.dataSource = new MatTableDataSource(ELEMENT_DATA);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
}
app.component.html
文件中添加以下代码:
ID
{{element.id}}
Name
{{element.name}}
Email
{{element.email}}
Phone
{{element.phone}}
相关内容