首页 > 解决方案 > 如何以角度过滤垫屑

问题描述

我正在做角度项目,我想让用户从现有标签(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 文件,因为它使用不同的组件

https://stackblitz.com/edit/angular-vcklft

标签: javascriptangularsearchfiltertags

解决方案


您可以执行以下描述的操作。

改变这个:

<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 演示


推荐阅读