我想知道如何使用搜索栏(https://stackblitz.com/edit/stackoverflowcom-a-60857864-6433166-dpaump)和下面的代码来使用其名称来过滤卡片。
这是我的Explore TS文件(我从其他文件导入了Matcard和路由器组件)
import { Router } from '@angular/router';
import { WorkspaceService } from 'src/app/core/services/workspace.service';
import { Workspace, WorkspaceType } from 'src/app/shared/models/workspace.model';
这是显示文件的HTML文件内部
<mc-workspace-card-list [workspaces] = "pubWorkspaces" [editable] = "false"></mc-workspace-card-list>
这就是现在的样子
[![在此处输入图片描述] [1]] [1]
注意:我没有在我的Stackblitz文件中包含上面的代码,因为其中涉及许多组件 我想知道是否有人可以通过仅查看上面的代码和stackblitz文件来为我实现该过滤器功能的提示,或者提示我。
答案 0 :(得分:3)
柑橘朋克的答案有效,但这是一些解释
HTML:
<input type="text"
[(ngModel)]="searchText" (ngModelChange)="searchTextChanged($event)" />
Ts:
在ngOnInit中,此forEach商店将pubWorkspaces复制到单独的数组中
workspaces.forEach(workspace => {
if(workspace.type == WorkspaceType.public){
this.pubWorkspaces.push(workspace);
}
});
this.filteredPubWorkSpaces= this.pubWorkspaces;
当搜索和即时通讯发生变化时,下面的函数将被调用,并假定您在pubws对象中具有name属性。
searchTextChanged(searchText){
//return array of workspace only having search text in their names
this.filteredPubWorkSpaces= this.pubWorkspaces.filter(pubws=>pubws.name.includes(searchText));
}
将其传递给组件
`<mc-workspace-card-list [workspaces] = "filteredPubWorkSpaces" [editable] = "false"></mc-workspace-card-list>`
答案 1 :(得分:1)
您可以添加显示结果的其他列表。 初始化组件时只需复制完整列表。在搜索栏更改事件上,您可以调用一个函数,该函数使用搜索词过滤原始列表并将其保存到其他变量中:
export class ExploreComponent implements OnInit, OnDestroy {
private workspaces;
public filteredWorkspaces;
public searchterm;
constructor(private workspaceService: WorkspaceService, private router: Router) { }
ngOnInit(): void {
this.loading = true;
this.workspaceService.getUserWorkspaces().subscribe((workspaces) =>{
workspaces.forEach(workspace => {
if(workspace.type == WorkspaceType.public){
this.pubWorkspaces.push(workspace);
}
this.filteredWorkspaces = workspaces;
}
onInputChange(){
this.filteredWorkspaces = this.workspaces.filter(ws => ws.name.includes(this.searchterm));
}