如何以角度过滤垫子芯片

时间:2020-03-25 19:06:33

标签: javascript angular search filter tags

我正在做角度项目,我想让用户从现有标签(芯片)中搜索/过滤。我有一个搜索框,可以过滤一个普通列表,但是当我尝试对标签进行过滤时,我不确定该怎么做。

我的垫子放在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

1 个答案:

答案 0 :(得分: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())
  );
}

[UPDATE] :我把这个stackblitz demo

放在一起了