【问题标题】:How to filter mat chips in angular如何以角度过滤垫屑
【发布时间】:2020-07-06 09:44:16
【问题描述】:

我正在做 Angular 项目,我想让用户从现有标签(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;
  }
}

这就是现在的样子

Picture

这就是我通常过滤普通列表/数据的方式

    <div [hidden]="!query">
    <div *ngFor="let name of users | search:query">{{ name }}</div>
    </div>

没有 mc-tags 的 Stackblitz 文件,因为它使用不同的组件

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

【问题讨论】:

  • 你能创建一个 stackBlitz 来检查它吗?
  • @Tzimpo 我刚刚创建了它(stackblitz.com/edit/angular-vcklft),但我没有包含 因为它是从不同的组件中使用的。交易
  • 我不确定我是否明白了……您希望用户单击一个芯片并使用所选芯片的值过滤用户数组,对吗?
  • @julianobrasil umm 现在,我只希望用户在搜索框中搜索芯片并仅显示匹配的芯片并隐藏其余芯片。 (不介意的话可以看我的附图)
  • 好吧...您只想开始输入芯片(标签)的名称并过滤它们。

标签: javascript angular search filter tags


【解决方案1】:

您可以按照下面的说明进行操作。

改变这个:

<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 demo

【讨论】:

  • 非常感谢您的帮助。真的很感激。
猜你喜欢
  • 1970-01-01
  • 2021-07-28
  • 2019-11-08
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
相关资源
最近更新 更多