要在Angular中创建一个带有搜索栏的表格,你可以按照以下步骤操作:
npm install -g @angular/cli
npm install -g typescript
ng new angular-table-search
cd angular-table-search
ng generate component table
table.component.html
文件,并添加以下代码:
Name
Email
{{ user.name }}
{{ user.email }}
table.component.ts
文件,并添加以下代码:import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
users = [
{ name: 'John Doe', email: 'john@example.com' },
{ name: 'Jane Doe', email: 'jane@example.com' },
{ name: 'Bob Smith', email: 'bob@example.com' },
// Add more users as needed
];
searchText: string;
filteredUsers: any[];
constructor() { }
ngOnInit() {
this.filteredUsers = this.users;
}
filterUsers() {
this.filteredUsers = this.users.filter(user => {
return user.name.toLowerCase().includes(this.searchText.toLowerCase()) ||
user.email.toLowerCase().includes(this.searchText.toLowerCase());
});
}
}
app.component.html
文件,并将以下代码添加到其中:
ng serve --open
现在,你应该可以在浏览器中看到一个带有搜索栏的表格。当你在搜索栏中输入文字时,表格将会自动过滤显示与搜索文本匹配的行。