javascript - 如何以角度过滤垫屑
问题描述
我正在做角度项目,我想让用户从现有标签(mat-chips)中搜索/过滤。我有一个搜索框,我可以过滤一个普通列表,但是当我尝试对标签执行此操作时,我不确定如何。
我的垫子在 home.component.html 里面。
<mc-tags [chips] = "tags" ></mc-tags>
我在 home.component.html 中的搜索框
<input matInput (input)="updateQuery($event.target.value)" class="input" >
list.ts 中的数据
export const tags = ['Google', 'Manufacturer'];
home.component.ts 文件
import { Component, OnInit } from '@angular/core';
import { users, tags } from './users.data';
@Component({
selector: 'mc-explore',
templateUrl: './explore.component.html',
styleUrls: ['./explore.component.scss']
})
export class ExploreComponent{
query: string;
users = users;
tags = tags;
updateQuery(query: string) {
this.query = query;
}
}
这就是它现在的样子
这就是我通常过滤普通列表/数据的方式
<div [hidden]="!query">
<div *ngFor="let name of users | search:query">{{ name }}</div>
</div>
没有 mc-tags 的 Stackblitz 文件,因为它使用不同的组件
解决方案
您可以执行以下描述的操作。
改变这个:
<input matInput (input)="updateQuery($event.target.value)" class="input" >
对此:
<input [formControl]="_inputCtrl" matInput class="input" >
并改变这个:
<mc-tags [chips] = "tags" ></mc-tags>
对此:
<mc-tags [chips]="_filteredTags" ></mc-tags>
将此代码添加到您的组件打字稿中:
_filteredTags = [];
_inputCtrl: FormControl = new FormControl();
private _destroy$ = new Subject<void>();
ngOnInit(): void {
this._filterTags();
this._inputCtrl.valueChanges
.pipe(takeUntil(this._destroy$))
.subscribe((value: string) => {
this._filterTags(value);
this.updateQuery(value);
});
}
ngOnDestroy(): void {
if (this._destroy$ && !this._destroy$.closed) {
this._destroy$.next();
this._destroy$.complete();
}
}
updateQuery(query: string) {
this.query = query;
}
private _filterTags(filterValue?: string) {
if (!filterValue) {
this._filteredTags = [...tags];
return;
}
this._filteredTags = this.tags.filter((v: string) =>
v.toLowerCase().includes(filterValue.toLowerCase().trim())
);
}
[更新]:我整理了这个stackblitz 演示
推荐阅读
- haskell - 是否可以拥有具有不同扩展名的 Haskell 源文件?
- r - R中同一图中的两个折线图
- reactjs - 自定义上传进度条 React
- python - 在python中更改CSV文件
- python - 如何使用 django 在 html 中调用聚合函数
- python - “传递的名称数与文件中的标题字段数不匹配”在 Pandas 中使用 read_excel 时出错
- laravel - 失败重定向到主页时的 Sanctum 表单请求验证
- c# - 深度 XML 序列化中的 C# for 循环
- angular - express deprecated res.send(status, body): 使用 res.status(status).send(body)
- linux - Linux 打印文件并在例如 curl 请求中使用它