[英]How to filter the data based on selected tab using mat-tab in Angular
我想弄清楚如何使用mat-tab
here根據選定選項卡的值過濾數據。 例如,我想要一個包含城市三個選項卡的選項卡面板: ALL
、 LA
、 SF
。 如果用戶單擊ALL
選項卡,它將在此處使用mat-card
顯示所有數據。 如果用戶選擇LA
,它將只顯示 LA 等人。
到目前為止,我只能在沒有過濾的情況下顯示所有數據。 這是我所做的最少代碼:
<mat-card *ngFor="let user of users">
<mat-card-header>
<mat-card-title>{{user.id}}</mat-card-title>
</mat-card-header>
<mat-card-content>{{user.city}}</mat-card-content>
</mat-card>
以下是數據示例:
const Users =
{
"users": [
{
"id": "person1",
"first_name": "Mike",
"last_name": "Patty",
"city": "LA"
},
{
"id": "person2",
"first_name": "Mike2",
"last_name": "Patty2",
"city": "LA"
},
{
"id": "person3",
"first_name": "Mike3",
"last_name": "Patty3",
"city": "SF"
},
{
"id": "person4",
"first_name": "Mike4",
"last_name": "Patty4",
"city": "SF"
}
]
}
如何響應選項卡顯示數據? 我感謝您的建議和幫助。
好吧,“正確”的方法可能是使用Pipes ,但我個人覺得這對於簡單的應用程序來說有點笨拙。 相反,我喜歡親吻並做這樣的事情:
html:
<button (click)='cityFilter = "LA"'>Los Angeles</button>
<div *ngFor="let user of getUsers(userlist.users)">
{{user.first_name}}
{{user.last_name}}
{{user.city}}
</div>
ts:
cityFilter: string;
userlist: any = {
users: [
{
id: 'person1',
first_name: 'Mike',
......
getUsers(users):any[] {
if (!this.cityFilter) return users;
return users.filter(u => u.city === this.cityFilter);
}
示例: https : //stackblitz.com/edit/angular-ivy-8s3qfe?file=src%2Fapp%2Fapp.component.ts
對於每個選項卡更改,您可以獲得selectedTabChange
事件。 通過此事件,您將過濾您的用戶。
在 html 文件中 -
<mat-tab-group (selectedTabChange)="tabChanged($event)">
<mat-tab *ngFor="let tabLabel of matTabLabels" label="{{tabLabel}}">
<mat-card *ngFor="let user of selectedUsers">
<mat-card-header>
<mat-card-title>{{user.id}}</mat-card-title>
</mat-card-header>
<mat-card-content>{{user.city}}</mat-card-content>
</mat-card>
</mat-tab>
</mat-tab-group>
在 .ts 文件中 -
selectedUsers: any;
matTabLabels = ['ALL', 'LA', 'SF'];
ngOnInit() {
this.selectedUsers = this.Users.users;
}
tabChanged(event: any) {
console.log(event);
if (event.index != 0) {
const filterText = event.tab.textLabel;
this.selectedUsers = this.Users.users.filter((user: any) => {
return user.city === filterText;
});
console.log(this.selectedUsers);
} else {
this.selectedUsers = this.Users.users;
}
}
工作 stackBlitz - https://stackblitz.com/edit/angular-qehpkb?file=src/app/tab-group-basic-example.ts
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.